表里数据如下
字段   A  ,   B,   C
       001   100   消费
       001   120   消费
       001   500   存储       002   80    消费
       002   100   消费
       002   500   存储select sum(B),A,C from table
group by A,C
得到以下记录
       sum(B),A,  C
        220      001  消费
        500      001   存储        180       002  消费
         500      002  存储如果我想按照以下形式显示,sql语句该怎么写
         
   id     消费  存储
   001    220    500
   002    180    500
         
      

解决方案 »

  1.   

    select 
      id,
      消费=sum(case when c='消费' then B else 0 end),
      存储=sum(case when c='存储' then B else 0 end)
    from
      [table]
    group by
      id
      

  2.   

    -- =========================================
    -- -----------t_mac 小编-------------
       ---希望有天成为大虾---- 
    -- =========================================IF OBJECT_ID('tb') IS NOT NULL
      DROP TABLE tb
    GO
    CREATE TABLE tb(a varchar(10),b int,c varchar(10))
    go
    insert into tb
    select  
    '001'  ,100 , '消费'  union all select 
    '001' , 120 , '消费' union all select 
    '001' , 500 , '存储' union all select 
    '002' , 80   , '消费' union all select 
    '002' , 100  ,'消费' union all select 
    '002' , 500  ,'存储' 
      go
    select ID=a,
    消费=SUM(case when c='消费' then b else 0 end),
    存储=SUM(case when c='存储' then b else 0 end)
    from tb 
    group by a
    /*------------
    ID         消费          存储
    ---------- ----------- -----------
    001        220         500
    002        180         500(2 行受影响)
    -------*/
      

  3.   

    --借小麦的数据说说case when  的另外一种用法
    IF OBJECT_ID('tb') IS NOT NULL
      DROP TABLE tb
    GO
    CREATE TABLE tb(a varchar(10),b int,c varchar(10))
    go
    insert into tb
    select  
    '001'  ,100 , '消费'  union all select 
    '001' , 120 , '消费' union all select 
    '001' , 500 , '存储' union all select 
    '002' , 80   , '消费' union all select 
    '002' , 100  ,'消费' union all select 
    '002' , 500  ,'存储' 
      goselect a as [ID],
    消费=SUM(case  c when '消费' then b else 0 end),
    存储=SUM(case  c when '存储' then b else 0 end)
    from tb 
    group by a
    /*ID         消费          存储          
    ---------- ----------- ----------- 
    001        220         500
    002        180         500(所影响的行数为 2 行)*/