Sql-Server
不同條件下如何計算不止一次?
有這樣一張桌子:
我想得到這樣的結果:
就像是:
SELECT ParentId, COUNT(SomeValue = 1) [CountMin], COUNT(SomeValue > 1) [CountRest] FROM MyTable GROUP BY ParentId
您可以使用 SUM(CASE…)
SELECT ParentID, SUM(CASE WHEN SomeValue = 1 THEN 1 ELSE 0 END) AS CountMin, SUM(CASE WHEN SomeValue <> 1 THEN 1 ELSE 0 END) AS CountRest FROM MyTable WHERE ParentID = 123;