【问题标题】:Can I select the variable in where clause in MSSQL?我可以在 MSSQL 的 where 子句中选择变量吗?
【发布时间】:2016-11-23 08:40:06
【问题描述】:

我想根据查询结果选择where子句中的变量。

Select table1.*, table2.color, table3.type
from table1
inner join table2 on table1.ID=table2.table1Id
inner join table3 on table1.ID=table3.table1Id
where table3.type = @x OR table3.type = @y

| productName | Category    | color | type |
| abc         | electronics | blue  |  x   |
| abc         | electronics | blue  |  y   |
| def         | electronics | red   |  x   |

这个查询可以返回重复的结果,因为产品可以有两种类型。我想在 where 子句中选择变量。例如,我想获取类型为@y 的产品,但如果产品的@y 类型不存在,我想返回@x 类型。我不希望示例结果中的第一个 abc 行。您能帮我解答一下我的问题吗?

【问题讨论】:

    标签: sql sql-server where-clause


    【解决方案1】:
    Select table1.*, table2.color, table3.type from table1
    inner join table2 on table1.ID=table2.table1Id inner join table3 on table1.ID=table3.table1Id where table3.type = CASE WHEN LEN(@x) > 0 THEN @x WHEN LEN(@y) > 0 THEN @y END
    

    【讨论】:

      【解决方案2】:

      您可以使用带有 order by 的相关查询:

      Select table1.*, table2.color,
             (SELECT TOP 1 table3.type
              FROM Table3
              WHERE table1.ID=table3.table1Id
              ORDER BY CASE WHEN table3.type = @y THEN 1 
                            WHEN table3.type = @x THEN 2
                            ELSE 3 END)
      from table1
       inner join table2 on table1.ID=table2.table1Id
       inner join table3 on table1.ID=table3.table1Id
      

      如果存在,相关查询将返回@y,如果不存在,将返回x

      【讨论】:

        【解决方案3】:

        使用 row_number() over() 从 table3 计算您想要的首选行

        SELECT
              table1.*
            , table2.color
            , t3.type
        FROM table1
        INNER JOIN table2 ON table1.ID = table2.table1Id
        INNER JOIN (
              SELECT
                    table3.table1Id
                  , table3.type
                  , ROW_NUMBER() OVER (PARTITION BY table3.table1Id
                                      ORDER BY table3.type DESC)    AS rn
              FROM table3
              ) t3 ON table1.ID = t3.table1Id
                    AND t3.rn = 1
        

        调整顺序以适应,例如它还可以包括一个案例表达式,例如

        ORDER BY case when t3.type = 'y' then 1 else 2 end, t3.type
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-28
          • 2010-10-31
          • 2017-07-18
          • 2017-05-07
          • 1970-01-01
          • 1970-01-01
          • 2012-04-28
          相关资源
          最近更新 更多