2016-04-06 17 views
0

私は以下のトラブルがあります。異なる条件のSQLカウント列

私のSQLテーブルには、次のようになります。

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

それを行うことが可能です:

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

私はこのように私の出力を持っていると思いますか?

私はこのような何かを試してみました:

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

? '' ZP ''はほとんどの場合、列ZPを意味しますが、ここではないかもしれません...? – jarlh

答えて

1

COUNTではなく、SUMCASEを使用してください。あなたのWHERE WITH句

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` 

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フィドル:DBMSは、使用しているhttp://sqlfiddle.com/#!9/ea161/3/0

+0

大変ありがとうございます。他のテーブルにユーザIDを持っているときに、ユーザ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

関連する問題