在PIVOT条件下需要一对多

时间:2019-01-25 11:01:44

标签: sql sql-server tsql

嗨,我有示例数据

Empid   Emp_Name    Dept    Part
1        Mohan     English  Part-1
1        Mohan     English  Part-2
1        Mohan     Maths    part-1
1        Mohan     Maths    part-2
2        Madhu     English  Part-1
2        Madhu     English  Part-2
2        Madhu     Maths    Part-1
2        Madhu     Maths    Part-2

使用Pivot,我会变成这样

Select Empid,Emp_Name,[maths],[english] from (
Select Empid,Emp_Name,Dept,part from  @tbl)T
PIVOT (MAX(part) FOR dept IN ( [maths],[english]))PVT

结果:

 Empid    Emp_Name      maths   english
    2        Madhu      Part-2  Part-2
    1        Mohan      part-2  Part-2

我如何获得这样的输出:

Empid   Emp_Name    maths   english
2        Madhu    Part-2    Part-2
2        Madhu    Part-1    Part-1
1        Mohan    part-2    Part-2
1        Mohan    part-1    Part-1

请问您对此有何建议

1 个答案:

答案 0 :(得分:1)

您需要摸索零件,因此可以进行条件聚合:

select empid, emp_name, 
       max(case when dept = 'maths' then part end) as maths,
       max(case when dept = 'english' then part end) as english
from (select *, row_number() over (partition by empid, emp_name, dept order by part) as seq
      from @tbl t
     ) t
group by empid, emp_name, seq
order by empid desc, maths desc, english desc;

如果要使用pivot版本,请在row_number()语句中使用inner select进行分组。