我可以在MSSQL的where子句中选择变量吗?

时间:2016-11-23 08:40:06

标签: sql sql-server where-clause

我想根据查询结果在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行。你能帮我解决一下我的疑问吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以按顺序使用相关查询:

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

答案 2 :(得分:0)

使用 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