我可以 select MSSQL where 子句中的变量吗?

Can I select the variable in where clause in MSSQL?

我想selectwhere子句中的变量根据查询结果

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   |

此查询可能 return 有重复的结果,因为产品有两种类型。我想 select where 子句中的变量。例如,我想获取类型为 @y 的产品,但如果产品的 @y 类型不存在,我想获取 return @x 类型。我不想要示例结果中的第一个 abc 行。你能帮我查询一下吗?

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

您可以将关联查询与排序方式结合使用:

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

相关查询将 return @y 如果存在,如果不存在,将 return x .

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

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

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