1

我必须编写一个连接 3 个表的查询。我有下表。

    Table Case
    CaseID  CaseType   CaseStatus
    001       1         2        
    002       2         1        
    003       3         4        

    Table Case Type
    TypeID    Name   
    1       Fraud            
    2       Duplicate    
    3       Other

最后是案例状态

    StatusID      Name   
    1             Resolved             
    2             Pending     
    3             Waiting   

我需要这样的结果

    Type          NumberofCase   Resolved    Pending   Waiting
    Fraud         1              1            0         0
    Duplicate     2              0            1         1
    Other         4              2            1         1

如果我不想使用临时表,我需要做什么。这如何通过 Col-case 或任何其他方法来完成。

4

2 回答 2

2

您可以使用join条件聚合来做到这一点:

select ct.Name as "Type", count(*) as NumberOfCase,
       sum(case when cs.Name = 'Resolved' then 1 else 0 end) as Resolved,
       sum(case when cs.Name = 'Pending' then 1 else 0 end) as Pending,
       sum(case when cs.Name = 'Waiting' then 1 else 0 end) as Waiting
from "case" c join
     CaseType ct
     on c.CaseType = ct.TypeId join
     CaseStatus cs
     on c.CaseStatus = cs.StatusId
group by ct.Name;
于 2013-09-17T11:14:42.747 回答
0

另一种方法是使用

Pivot() Over()
于 2013-09-17T11:22:35.603 回答