SQL Server联盟选择与不同'其中'单行的子句

时间:2017-01-31 15:29:17

标签: sql sql-server sql-server-2014

目前,我正在列出一组数据,其中包含单独的" UNION" ed select语句,为每条信息创建一个新的行条目:

示例:

  (No column name)
1  40
2  11
3  13
4  29
5  64
6  34

我想要的是将其更改为带有标记列的行。

示例:

  Column 1   Column 2   Column 3   Column 4   Column 5   Column 6
1   40          11         13         29         64         34

我将如何做到这一点?

1 个答案:

答案 0 :(得分:4)

DECLARE @T TABLE (Val INT, SortOrder VARCHAR(20))
INSERT INTO @T
SELECT 40,'Column 1'
UNION
SELECT 11,'Column 2'
UNION
SELECT 13,'Column 3'
UNION
SELECT 29,'Column 4'
UNION
SELECT 64,'Column 5'
UNION
SELECT 34,'Column 6'

SELECT * FROM @T
pivot (avg (Val) for SortOrder in (
 [Column 1],[Column 2],[Column 3],[Column 4],[Column 5],[Column 6])
) as Whatever

rextester:http://rextester.com/LWZH64528

结果:

+----------+----------+----------+----------+----------+----------+
| Column 1 | Column 2 | Column 3 | Column 4 | Column 5 | Column 6 |
+----------+----------+----------+----------+----------+----------+
|       40 |       11 |       13 |       29 |       64 |       34 |
+----------+----------+----------+----------+----------+----------+

日期作为第一列值

DECLARE @T TABLE (Val VARCHAR(20), SortOrder VARCHAR(20))
INSERT INTO @T
SELECT '2016-10-12','Column 1'
UNION
SELECT '11','Column 2'
UNION
SELECT '13','Column 3'
UNION
SELECT '29','Column 4'
UNION
SELECT '64','Column 5'
UNION
SELECT '34','Column 6'

SELECT * FROM @T
pivot (MAX(Val) for SortOrder in ([Column 1],[Column 2],[Column 3],[Column 4],[Column 5],[Column 6])) as Whatever

结果:

+----------+----------+----------+----------+----------+----------+
| Column 1 | Column 2 | Column 3 | Column 4 | Column 5 | Column 6 |
+----------+----------+----------+----------+----------+----------+
|2016-10-12|       11 |       13 |       29 |       64 |       34 |
+----------+----------+----------+----------+----------+----------+