SQL:WHERE子句中的匹配计数

时间:2016-10-14 04:29:54

标签: sql sql-server

我需要在SELECT语句的WHERE子句中找到匹配的表达式数。样本数据和表格如下:

    declare @var1 varchar(10), @var2 varchar(10), @var3 varchar(10)
set @var1 = 'a'
set @var2 = null
set @var3 = 'c'
insert into tempTable values(1, 'a', 'b', 'c')
insert into tempTable values(2, 'a', 'e', 'c')
insert into tempTable values(3, 'g', 'b', 'c')

select id from tempTable
where   ISNULL(@var1, colA) = colA
AND     ISNULL(@var2, colB) = colB
AND     ISNULL(@var3, colC) = colC

输出应该是这样的:

 id     MatchingCount
 ------------------------
1       2  (because @var1 and @var3 are matched)
2       2  (because @var1 and @var3 are matched)

感谢。

3 个答案:

答案 0 :(得分:1)

select id, cast ((case when @var1 = colA then 1 else 0 end) as int) 
          +cast ((case when @var2 = colB then 1 else 0 end) as int)
          +cast ((case when @var3= colC then 1 else 0 end) as int) as MatchCount
from tempTable

用例

答案 1 :(得分:0)

您可以从以下查询中获得相同的结果,我认为这对您的要求更好,您可以轻松实现:

SELECT id, 
 SUM((CASE WHEN @var1 IN (colA, ColB, ColC) THEN 1 ELSE 0 END) +
    (CASE WHEN @var2 IN (colA, ColB, ColC) THEN 1 ELSE 0 END) +
    (CASE WHEN @var3 IN (colA, ColB, ColC) THEN 1 ELSE 0 END)) cnt  
FROM #tempTable
GROUP BY id

没有分组,

SELECT id, 
    ((CASE WHEN @var1 IN (colA, ColB, ColC) THEN 1 ELSE 0 END) +
    (CASE WHEN @var2 IN (colA, ColB, ColC) THEN 1 ELSE 0 END) +
    (CASE WHEN @var3 IN (colA, ColB, ColC) THEN 1 ELSE 0 END)) cnt  
FROM #tempTable

答案 2 :(得分:0)

认为它可以帮助你

 p.setRed(red);
 p.setGreen(green);
 p.setBlue(blue);