2016-04-06 41 views
0

我有以下麻煩。不同條件下的SQL計數列

我的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 

任何人都可以幫我嗎?

+1

哪個DBMS您使用的? 「ZP」在大多數情況下表示ZP列,但也許不在這裏......? – jarlh

回答

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

+0

非常感謝你,以及如果我想更改用戶名到其他表中的名稱,我有用戶ID |名稱 ?? –

+0

有點像'name where user = sub.user'的子查詢 – Matt

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 
+0

@martin讓我知道它符合您的要求 – mohan111