用于在SQL Server 2008中将列显示为行的查询。

用于在SQL Server 2008中将列显示为行的查询。,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我必须编写一个连接3个表的查询。我有以下表格 Table Case CaseID CaseType CaseStatus 001 1 2 002 2 1 003 3 4 Table Case Type TypeID Name 1 Fraud

我必须编写一个连接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或任何其他方法实现这一点

您可以使用
连接
和条件聚合来完成此操作:

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;

另一种方法是使用

Pivot() Over()