如何将Table1表,整理成Table2,其中一个合同号只对应一个工长与监理,没有的为空或0显示Table1合同号  职务  姓名  数量  提成
001     工长  李    2     200
001     工长  李    3     400
001     监理  王    2     300
001     监理  王    5     500
002     工长  赵    1     100Table2合同号  工长  数量  工长提成  监理  数量  监理提成
001     李    5      600      王    7     800
002     赵    1      100            0      0 

解决方案 »

  1.   


    --如果百度了还是不会再看下面的--> 测试数据: [tb]
    if object_id('[tb]') is not null drop table [tb]
    create table [tb] (合同号 varchar(3),职务 varchar(4),姓名 varchar(2),数量 int,提成 int)
    insert into [tb]
    select '001','工长','李',2,200 union all
    select '001','工长','李',3,400 union all
    select '001','监理','王',2,300 union all
    select '001','监理','王',5,500 union all
    select '002','工长','赵',1,100--开始查询
    select 合同号,
    工长=MAX(case when 职务='工长' then 姓名 else '0' end),
    数量=SUM(case when 职务='工长' then 数量 else 0 end),
    工长提成=SUM(case when 职务='工长' then 提成 else 0 end),
    监理=MAX(case when 职务='监理' then 姓名 else '0' end),
    数量=SUM(case when 职务='监理' then 数量 else 0 end),
    监理提成=SUM(case when 职务='监理' then 提成 else 0 end)
    from [tb]
    group by 合同号--结束查询
    drop table [tb]/*
    合同号  工长   数量          工长提成        监理   数量          监理提成
    ---- ---- ----------- ----------- ---- ----------- -----------
    001  李    5           600         王    7           800
    002  赵    1           100         0    0           0(2 行受影响)