Sql-Server
用 where 子句計數
有沒有辦法在 COUNT 中有 WHERE 子句?或者如何計算一些條款?
select a b, count(c where t1.u='UAE') as c1 from t1
我正在使用 MS SQL Server 2014
不,您的語法無效,可以通過使用
CASE
表達式來糾正。(我猜你有
GROUP BY a, b
一個錯誤,否則你會得到一個錯誤)。select a b, count(case when t1.u = 'UAE' then c else null end) as c1 from t1 group by a, b ;
請注意,這
ELSE NULL
是多餘的,可以刪除,因為這是預設ELSE
行為:select a b, count(case when t1.u = 'UAE' then c end) as c1 from t1 group by a, b ;
有一種(SQL 標準)
FILTER
語法接近您的嘗試,但 SQL Server 尚未實現它:select a b, count(c) filter (where t1.u = 'UAE') as c1 from t1 group by a, b ;
SELECT DISTINCT a.a ,a.b ,b.c1 FROM t1 a INNER JOIN ( SELECT a ,b ,COUNT(u) AS c1 FROM t1 WHERE u = 'UAE' GROUP BY a ,b ) b ON a.a = b.a AND a.b = b.b
只是另一種方式。