行到多行的列

时间:2014-09-16 07:05:19

标签: sql sql-server

我正在寻找以下列方式将行转换为列 下面是示例表mytable。

myTable的

id |Dept_id |Emp_id
---+--------+----
1  |10      |1001
2  |10      |1002
3  |10      |1003
4  |20      |2001
5  |20      |2002
6  |20      |2003

so on....

预期结果

column1 | column2 | column3
--------+---------+--------
1001    |1002     |1003
2001    |2002     |2003
3001    |3002     |3003

我尝试使用PIVOT以下方式,但我得到的结果为

QUERY

select *
from
(
  select Emp_id, Dept_id 
  from myTable
)d
pivot
(
  MAX(Emp_id)
  for Dept_id in ([10],[20],[30])
) piv

但我得到的只是一行

10      | 20      | 30
--------+---------+-------
1003    |2003     |3003

我们正在使用SQL Server 2008。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下查询

SELECT *
FROM
(
  SELECT Emp_id, Dept_id, 'Column' + CAST(RowNum AS VARCHAR(10)) AS ColumnName
  FROM
  (
      SELECT Emp_id, 
             Dept_id, 
             ROW_NUMBER() OVER(PARTITION BY Dept_id ORDER BY Emp_id) AS RowNum  
      FROM myTable
  ) AS mainTable
)d
PIVOT
(
  MAX(Emp_id)
  FOR ColumnName IN ([Column1],[Column2],[Column3])
) piv

答案 1 :(得分:0)

以下是使用交叉表的另一种解决方案:

with cte as(
    select
        *,
        row_number() over(partition by Dept_Id order by Emp_Id) as rn
    from myTable
)
select
    max(case when rn = 1 then Emp_Id end) as column1,
    max(case when rn = 2 then Emp_Id end) as column2,
    max(case when rn = 3 then Emp_Id end) as column3
from cte
group by Dept_Id