Sql-Server

不同條件下如何計算不止一次?

  • March 1, 2019

有這樣一張桌子:

範例表

我想得到這樣的結果:

結果

就像是:

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;

引用自:https://dba.stackexchange.com/questions/231106