我想基于条件条件过滤查询,例如,如果ProjectId equals 1
则根据某个条件过滤,否则,将根据另一个不同条件进行过滤:
如果可能的话,在SQL中看起来像这样:
SELECT * FROM [dbo].[Commits]
WHERE CASE WHEN ProjectId=1 THEN (CommitsCount > 2) ELSE (Name LIKE 'R%') END
示例:
ProjectId Name CommitsCount
----------- --------- -----------
1 Ahmed 2
1 Ahmed 6
2 Kamel 10
3 Rami NULL
查询所需要的结果是:
ProjectId Name CommitsCount
----------- --------- -----------
1 Ahmed 6
3 Rami NULL
答案 0 :(得分:2)
不建议在case
子句中使用where
条件。原因之一是它们阻碍了查询的优化。另一个就是根本不需要它们,因此使条件变得比必要的更为复杂。
所以我建议:
select c.*
from dbo.commits c
where (c.ProjectId = 1 and c.CommitsCount > 2) or
(c.ProjectId <> 1 and c.Name = 'R&');
答案 1 :(得分:1)
您可以使用:
SELECT *
FROM [dbo].[Commits]
WHERE (CASE WHEN ProjectId = 1 AND CommitsCount > 2 THEN 1
WHEN ProjectId != 1 AND Name LIKE 'R%' THEN 1
END) = 1
(Name ='R&')
=> Name LIKE 'R%'