在单行中按记录分组显示

时间:2018-09-11 17:08:31

标签: sql-server

我有一张桌子,如下:

DeptName     year
------------------
Engineering  2001
Sales        2001
Tool Design  2001
Engineering  2002
Sales        2002
Tool Design  2002
Engineering  2003
Sales        2003
Tool Design  2003

我需要按部门名称分组并在单行中显示,如下所示:

DeptName     year  DeptName year DeptName year
------------------ ----------------------------
Engineering 2001 Sales    2001  Tool Design  2001 
Engineering 2002 Sales    2002  Tool Design  2002 
Engineering 2003 Sales    2003  Tool Design  2003

1 个答案:

答案 0 :(得分:-1)

听起来您实际上想group by year字段。假设您知道所有部门,这是使用conditional aggregationpivot结果的一种选择:

select year, 
      max(case when deptname = 'Engineering' then deptname end) deptname1,
      max(case when deptname = 'Sales' then deptname end) deptname2,
      max(case when deptname = 'Tool Design' then deptname end) deptname3
from yourtable
group by year

如果您不知道部门,则需要改用dynamic sql