我的SQL查询有问题
我有
T1:
ID STATUS REPORTEDBY
1 CLOSED USER1
2 CLOSED USER2
3 NEW USER1
4 INPRG USER1
5 CLOSED USER1
T2:
T1ID STATUS
1 NEW
1 CHECKING
1 CLOSED
2 NEW
2 CHECKING
2 CLOSED
3 NEW
4 CHECKING
4 INPRG
5 INPRG
5 CLOSED
结果我想得到这个:
USER NumberHasCHECKING NumberDifferentFromNewChecking NumberClosed
USER1 2 3 2
USER2 1 1 1
我想通过REPORTEDBY字段获取结果组
来自T1的记录数量,在T2中存在CHECKING状态,
来自T1的记录数目,其状态与NEW或T1中的CHECKING不同
和T1中当前处于CLOSED状态的记录数。
select reportedby,count (case when T2.status='CHECKING' then 1 end) as NumberHasChecking,
count (case when T2.status not in ('NEW','CHECKING') then 1 end) as NumberDifferentFromNewChecking,
count (case when T1.status='CLOSED' then 1 end) as NumberClosed
from t1
inner join t2 on T1.ID=T2.T1ID
group by reportedby
但是在我进行内部联接后,我在第二和第三列获得了更大的结果。 怎么解决这个? 谢谢
答案 0 :(得分:0)
不确定这是否适用于DB2:
Select
ReportedBy,
Count (Case When t2.Status = 'CHECKING' Then 1 End) As NumberHasChecking,
Count (Distinct Case When t1.Status Not In ('NEW','CHECKING') Then t1.Id End) As NumberDifferentFromNewChecking,
Count (Distinct Case When t1.Status = 'CLOSED' Then t1.Id End) As NumberClosed
From
t1
Inner Join
t2
on t1.Id = t2.t1Id
Group By
ReportedBy
答案 1 :(得分:0)
试试这个:
select
reportedby,
sum (T2.CheckingState) as NumberHasChecking,
count (case when T1.status not in ('NEW','CHECKING') then 1 end) as NumberDifferentFromNewChecking,
count (case when T1.status='CLOSED' then 1 end) as NumberClosed
from
T1 inner join
(
SELECT
T1ID,
COUNT(CASE WHEN STATUS='NEW' THEN 1 END) NewState,
COUNT(CASE WHEN STATUS='CHECKING' THEN 1 END) CheckingState,
COUNT(CASE WHEN STATUS='CLOSED' THEN 1 END) ClosedState
FROM T2
GROUP BY T1ID
) T2 ON T1.ID=T2.T1ID
group by reportedby