使用两个不同的子句计算两列的行数

时间:2015-09-01 04:59:47

标签: sql sql-server common-table-expression

我在CTE之后想要返回两列,一列总数为1,另一列总数为0' s。目前我可以使用以下命令返回一个总数为1的列:

WITH getOnesAndZerosCTE
AS (

    SELECT COUNT([message]) AS TotalNo1s
    FROM dbo.post
    WHERE dbo.checkletters([message]) = 1

    --SELECT COUNT([message]) AS TotalNo0s
    --FROM dbo.post
    --WHERE dbo.checkletters([message]) = 0

    )
SELECT * FROM getOnesAndZerosCTE;

我如何在同一个CTE中有一个名为TotalNo0s的第二列,我在那里评论过以表明我的意思。

3 个答案:

答案 0 :(得分:4)

使用条件聚合:

WITH getOnesAndZerosCTE AS(
    SELECT
        TotalNo1s = SUM(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 ELSE 0 END),
        TotalNo0s = SUM(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 ELSE 0 END)
    FROM post
)
SELECT * FROM getOnesAndZerosCTE;

答案 1 :(得分:1)

直接使用COUNT()时,请注意它会计算任何NON-NULL值。您可以省略ELSE条件,如果未声明则隐式返回NULL

SELECT
    COUNT(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 END) TotalNo1s 
  , COUNT(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 END) TotalNo0s
FROM post

或显式地声明NULL

SELECT
    COUNT(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 ELSE NULL END) TotalNo1s 
  , COUNT(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 ELSE NULL END) TotalNo0s
FROM post

答案 2 :(得分:0)

你可以在没有CTE的情况下完成

select    count(message) total,  
          dbo.checkletters(message) strLength 
from      post
group by  dbo.checkletters(message)
having    dbo.checkletters(message) in  (1, 2) //All the messages with length 1 or 2