--这个是待查询表
select 10 as 金额,'美元' 币种,12 房间
union all 
select 20,'港币',12
union all 
select 40,'美元',11
union all 
select 10,'人民币',11
union all 
select 10,'人民币',11
union all 
select 10,'人民币',12--这个是查询结果表
select 11 房间,20 人民币,40 美元,0 港币
union all
select 12 房间,10 人民币,10 美元,20 港币请问用一条SQL实现按照房间group by 然后分别汇总 人民币 美元 港币 
只能用一条SQL。  其中 三个币种是固定的。不会有新的币种出来。

解决方案 »

  1.   

    select 房间,人民币,美元,港币 from
    (
    select 10 as 金额,'美元' 币种,12 房间
    union all 
    select 20,'港币',12
    union all 
    select 40,'美元',11
    union all 
    select 10,'人民币',11
    union all 
    select 10,'人民币',11
    union all 
    select 10,'人民币',12
    ) t
    pivot
    (sum(金额) for 币种 in (人民币,美元,港币)) p
      

  2.   

    --> 测试数据:[TB]
    if object_id('[TB]') is not null
    drop table [TB]---->建表
    create table [TB]([金额] int,[币种] varchar(48),[房间] varchar(78))
    insert [TB]
    select 10 ,'美元',12 
    union all  
    select 20,'港币',12
    union all  
    select 40,'美元',11
    union all  
    select 10,'人民币',11
    union all  
    select 10,'人民币',11
    union all  
    select 10,'人民币',12--> 查询结果
    SELECT 房间,
    SUM(case 币种 when '人民币' then 金额 else 0 end )as 人民币, 
    SUM(case 币种 when '美元' then 金额 else 0 end )as 美元, 
    SUM(case 币种 when '港币' then 金额 else 0 end )as 港币 
    FROM [TB]
    group by 房间