有一张表 A,数据如下:
【姓名】   【重量】 【类别】张三 50          入库
李四 10          入库
王五 30          入库
张三     20          倒库
李四 10    倒库
王五 20    倒库
王五     30          出库
赵虎 30          出库我想得到结果:【姓名】   【入库】   【倒库】   【出库】
张三        50          20          0
李四        10          10          0
王五        30          20          30
赵虎        0            0          30
(备注:还有一个人员表,里面存有所有的人员)

解决方案 »

  1.   


    select 姓名,
        sum(case when 类别='入库' then 数量 else 0 end) 入库,
        sum(case when 类别='出库' then 数量 else 0 end) 出库,
        sum(case when 类别='倒库' then 数量 else 0 end) 倒库
    from tb
    group by 姓名
      

  2.   

    select 姓名,
        sum(case when 类别='入库' then 数量 else 0 end) '入库',
        sum(case when 类别='出库' then 数量 else 0 end) '出库',
        sum(case when 类别='倒库' then 数量 else 0 end) '倒库'
    from tb
    group by 姓名
      

  3.   


    declare @test table(姓名 nvarchar(3),重量 int,类别 nvarchar(2))
    insert into @test
    select N'张三', 50, N'入库' union all
    select N'李四', 10, N'入库' union all
    select N'王五', 30, N'入库' union all
    select N'张三', 20, N'倒库' union all
    select N'李四', 10, N'倒库' union all
    select N'王五', 20, N'倒库' union all
    select N'王五', 30, N'出库' union all
    select N'赵虎', 30, N'出库'
    select t.姓名,
    入库=isnull((select sum(重量) from @test where 姓名=t.姓名 and 类别=N'入库'),0),
    倒库=isnull((select sum(重量) from @test where 姓名=t.姓名 and 类别=N'倒库'),0),
    出库=isnull((select sum(重量) from @test where 姓名=t.姓名 and 类别=N'出库'),0)
    from
    (select distinct 姓名 from @test) t
    /*
    姓名   入库          倒库          出库
    ---- ----------- ----------- -----------
    张三   50          20          0
    李四   10          10          0
    王五   30          20          30
    赵虎   0           0           30
    */