如何检索单行数据?

时间:2015-05-11 14:17:33

标签: sql-server

我有一个包含一些数据的表,如下所示:

+---------+---------+---------+---------+-------------+
| Column1 | Column2 | Column3 | Column4 |   Column5   |
+---------+---------+---------+---------+-------------+
| 38073   |      16 | abc     |     444 | 4/28/2015   |
| 38076   |      70 | gug     |     555 | 4/30/2015   |
| 38098   |      13 | yyy     |     111 | 5/12/2015   |
| 38098   |      13 | yyy     |     112 | 5/13/2015   |
| 38098   |      13 | yyy     |     113 | 5/14/2015   |
| 38098   |      13 | yyy     |     114 | 5/15/2015   |
| 38100   |      17 | abc     |     115 | 5/13/2015   |
+---------+---------+---------+---------+-------------+

我想要做的是将第4列和第5列中的值放在一行,如下所示:

+---------+----------+-----------+----------+-----------+----------+-----------+----------+-------------+
|  Col1   | Col4Val1 | Col5Val1  | Col4Val2 | Col5Val2  | Col4Val3 | Col5Val3  | Col4Val4 |  Col5Val4   |
+---------+----------+-----------+----------+-----------+----------+-----------+----------+-------------+
| 38073   |      444 | 4/28/2015 | null     | null      | null     | null      | null     | null        |
| 38076   |      555 | 4/30/2015 | null     | null      | null     | null      | null     | null        |
| 38098   |      111 | 5/12/2015 | 112      | 5/13/2015 | 113      | 5/14/2015 | 114      | 5/15/2015   |
+---------+----------+-----------+----------+-----------+----------+-----------+----------+-------------+

尽可能感谢帮助。

谢谢。

的Bogdan

1 个答案:

答案 0 :(得分:0)

您可以使用UNION通过CTE,然后使用PIVOT列来取消数据。你也可以动态地实现这一点,有数百篇文章将告诉你如何做到这一点:

;WITH CTE AS (
SELECT [Column1], CAST([Column4] AS VARCHAR) AS [ColumnVals], 'Col4Val'+CAST(ROW_NUMBER() OVER(PARTITION BY [Column1] ORDER BY (SELECT 1)) AS VARCHAR) AS [Pivot]
FROM  Table1
UNION
SELECT [Column1], [Column5], 'Col5Val'+CAST(ROW_NUMBER() OVER(PARTITION BY [Column1] ORDER BY (SELECT 1)) AS VARCHAR) AS [Pivot]
FROM  Table1)
SELECT [Column1], [Col4Val1], [Col5Val1], [Col4Val2], [Col5Val2], [Col4Val3], [Col5Val3], [Col4Val4], [Col5Val4]
FROM CTE
PIVOT (MAX([ColumnVals]) FOR [Pivot] IN ([Col4Val1], [Col5Val1], [Col4Val2], [Col5Val2], [Col4Val3], [Col5Val3], [Col4Val4], [Col5Val4])) PIV

这是一个工作小提琴:http://sqlfiddle.com/#!6/e992f/1