如何计算一次查询的总启用和禁用行?

时间:2013-08-22 05:38:43

标签: sql

例如。

id name age status
1  aaa  10  1
2  bbb  20  0
3  ccc  30  1

现在如何从单个查询中计算总状态1和0 Ans将是1 => 2和0 => 1

2 个答案:

答案 0 :(得分:2)

要获得一行,这是我认为你要求的,请使用条件SUM s:

SELECT SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS status1,
    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS status0
FROM Table1

要获得多行,只需GROUP BY状态:

SELECT status, COUNT(1) AS rows
FROM Table1
GROUP BY status

答案 1 :(得分:1)

请尝试:

SELECT 
    STATUS, 
    COUNT(*) Total 
FROM 
    YourTable
GROUP BY STATUS

OR

SELECT DISTINCT
    STATUS, 
    COUNT(*) OVER (PARTITION BY STATUS) Total 
FROM 
    YourTable