2016-04-06 12 views
0

Aşağıdaki sorunları yaşıyorum.Farklı koşullarda SQL sayımı sütunu

My SQL tablosu aşağıdaki görünür:

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

Bu gibi benim çıkışı istiyorum:

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

mümkün mü bunu?

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 

kimse bana yardım edebilir:

böyle bir şey denedi?

+1

kullanıyorsunuz vtys? "ZP", çoğu durumda sütun ZP anlamına gelir, ama belki de burada değil ...? – jarlh

cevap

1

COUNT yerine SUM ve CASE kullanın.

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 yan tümce.

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` 

Çıktı

user countZP countNP 
2002 1  1 
2003 1  1 

SQL Fiddle: Eğer http://sqlfiddle.com/#!9/ea161/3/0

+0

wow çok teşekkür ederim ve kullanıcı kimliğini değiştirmek istediğimde başka bir masada ne zaman kullanıcı kimliği var id | isim mi ?? –

+0

Kullanıcı adı altında bir alt sorgu gibi bir şey var = 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, ihtiyacınızı karşıladığını bana bildirin – mohan111

İlgili konular