T-SQL两个使用不同的where子句计数

时间:2018-05-22 21:27:04

标签: tsql sql-server-2014

我想在具有不同where子句的表上计算值,并想知道是否有更好的方法。

在这段代码中我算一个值。

SELECT v.name, count(v.value) AS v1
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value = 1
GROUP BY v.name

我还想计算value = 2的所有行 我这样做的方式是这样的子选择。

SELECT v.name, count(v.value) AS v1, (SELECT v2.name, count(v2.value)  
FROM dbo.table as v2
WHERE v2.organisationID = 2
AND v2.datecreated > '2018-01-01'
AND v2.datecreated < '2018-05-01'
AND v2.value = 2
GROUP BY v2.name) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value = 1
GROUP BY v.name

该表包含&gt; 1亿行,所以我真的想要最快的方式。我在表上使用了聚集列存储索引。

是否有某种方法可以通过子选择进行。

伪代码:

SELECT v.name, count(v.value where v.value=1) AS v1, count(v.value where v.value=2) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
GROUP BY v.name

1 个答案:

答案 0 :(得分:3)

是的,只需使用CASE表达式:

SELECT  v.name, 
        SUM(CASE WHEN v.value = 1 THEN 1 ELSE 0 END) AS v1,
        SUM(CASE WHEN v.value = 2 THEN 1 ELSE 0 END) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value IN (1,2)
GROUP BY v.name
;