不同条件下的SQL计数列

时间:2016-04-06 08:24:24

标签: sql join count group-by

我遇到了麻烦。

我的SQL表看起来如下:

 | lead_id | user | status |
 | 1       | 2002 | ZP     |
 | 2       | 2003 | ZP     |
 | 3       | 2002 | NP     |
 | 4       | 2003 | NP     |

我希望我的输出像这样:

 | user | countZP | countNP |
 | 2002 |    1    |    1    |
 | 2003 |    1    |    1    |

有可能吗?

我试过这样的事情:

select user, count(a.status) as countZP, count(b.status) as countNP
from mytable a
join mytable b on a.lead_id = b.lead_id
where a.status = "ZP" or b.status = "NP"
group by user

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

使用SUMCASE而不是COUNT

SELECT `user`,  
SUM(CASE WHEN `status` = 'ZP' THEN 1 ELSE 0 END) AS countZP,
SUM(CASE WHEN `status` = 'NP' THEN 1 ELSE 0 END) AS countNP
FROM mytable
GROUP BY `user`

使用WHERE条款。

SELECT `user`,  
SUM(CASE WHEN `status` = 'ZP' THEN 1 ELSE 0 END) AS countZP,
SUM(CASE WHEN `status` = 'NP' THEN 1 ELSE 0 END) AS countNP
FROM mytable
WHERE `status` IN ('ZP', 'NP')
GROUP BY `user`

输出

user  countZP  countNP
2002  1        1
2003  1        1

SQL小提琴:http://sqlfiddle.com/#!9/ea161/3/0

答案 1 :(得分:0)

DECLARE @Table1  TABLE 
    ( lead  int,  users  int,  status  varchar(2))
;

INSERT INTO @Table1
    ( lead ,  users ,  status )
VALUES
    (1, 2002, 'ZP'),
    (2, 2003, 'ZP'),
    (3, 2002, 'NP'),
    (4, 2003, 'NP')
;
Select users,MAX([ZP]) AS countZP,MAX([NP]) AS countNP from (
select lead ,  users ,  status ,count(status)S from @Table1
GROUP BY lead ,  users ,  status)T


PIVOT(MAX(S) FOR status IN ([ZP],[NP]))P
GROUP BY USERS