1

我的 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 字段作为结果组

  1. T1 中在 T2 中存在 CHECKING 状态的记录数,

  2. 来自 T1 的记录数,现在处于与 T1 中的 NEW 或 CHECKING 不同的状态

  3. 以及 T1 中当前处于 CLOSED 状态的 T1 中的记录数。

.

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

但是在我进行内部连接之后,我在第二列和第三列得到了更好的结果。如何解决这个问题?谢谢你

4

2 回答 2

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
于 2012-12-23T21:02:54.227 回答
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
于 2012-12-23T21:13:13.983 回答