SQL服务器PIVOT与行分组

时间:2014-09-21 05:25:55

标签: sql-server pivot

我有一个看起来像这样的表:

表格

+------+----------+
| CODE | DATE     |
+======+==========+
|  A   | 6/30/14  |
|  A   | 3/31/14  |
|  A   | 12/31/13 |
|  A   | 9/30/13  |
|  B   | 5/31/14  |
|  B   | 2/28/14  |
|  B   | 11/30/13 |
|  B   | 8/31/14  |
|  C   | 6/27/14  |
|  C   | 3/28/14  |
|  C   | 12/27/13 |
|  C   | 9/27/13  |
+------+----------+

我需要输出看起来像这样:

预期输出

+-------+-----------+----------+-----------+----------+
| CODE  |  DATE_1   | DATE_2   |  DATE_3   |  DATE_4  |
+=======+===========+==========+===========+==========+
|  A    |  6/30/14  | 3/31/14  | 12/31/13  | 9/30/13  |
|  B    |  5/31/14  | 2/28/14  | 11/30/13  | 8/31/14  |
|  C    |  6/27/14  | 3/28/14  | 12/27/13  | 9/27/13  |
+-------+-----------+----------+-----------+----------+

每个代码值(A,B,C)显示4次,因此DATE_1,DATE_2,DATE_3和DATE_4字段不会更改。有人可以帮忙??

1 个答案:

答案 0 :(得分:0)

使用PIVOT可以实现此目的。

<强> QUERY

SELECT code,
[1] AS DATE_1,
[2] AS DATE_2,
[3] AS DATE_3,
[4] AS DATE_4
FROM
(
  SELECT code, dt, 
  row_number() over 
  (
     partition by code 
     ORDER BY code
  ) rn
  FROM tbl
) t
PIVOT 
(
  MIN (dt) FOR rn IN 
  (
     [1], [2], [3], [4]
  )
) pvt

FIND FIDDLE HERE