2016-11-23 94 views
1

我想根據查詢結果在where子句中選擇變量。我可以在MSSQL的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行。你能幫我解答一下嗎?

回答

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 
+0

謝謝。有效。 –

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

0

使用ROW_NUMBER()以上()計算優選行你從表3

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