如何转动结果查询?
目前看起来像这样
Hours | Volume
8 | 1000
9 | 1012
10 | 1045
11 | 1598
12 | 1145
13 | 1147
进入这个
8 |9 |10 |11 |12 |13
1000|1012|1045|1598|1145|1147
我尝试了以下但是它不能正常工作
Select #TEMP.volume,
pvt.volume,
#TEMP.volume
pvt.volume
FROM #TEMP
PIVOT (volume FOR [DialHour] IN ( "8", "9", "10", "11","12","13","14","15","16","17","18","19")) AS pvt
答案 0 :(得分:1)
你可以在technet上找到一个明确的例子; https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
您的代码应该更像下面的内容;
Select volume, [8], [9], [10], [11],[12],[13],[14],[15],[16],[17],[18],[19]
FROM
(SELECT volume FROM #TEMP) AS SourceTable
PIVOT
(
hours
FOR volume IN ("8", "9", "10", "11","12","13","14","15","16","17","18","19")
) AS PivotTable;
答案 1 :(得分:1)
我在T-SQL中创建此表以进行演示。
CREATE TABLE #TEMP (HOURS INT, VOLUME INT)
INSERT INTO #TEMP VALUES
(8 ,1000),
(9 ,1012),
(10,1045),
(11,1598),
(12,1145),
(13,1147)
;
如果您不使用T-SQL(SQL Server),则可能会遇到Pivot示例的问题。不同平台的语法不同。这是一种更标准的方法。
SELECT
MAX(CASE WHEN HOURS = 8 THEN VOLUME END) AS [8]
,MAX(CASE WHEN HOURS = 9 THEN VOLUME END) AS [9]
,MAX(CASE WHEN HOURS = 10 THEN VOLUME END) AS [10]
,MAX(CASE WHEN HOURS = 11 THEN VOLUME END) AS [11]
,MAX(CASE WHEN HOURS = 12 THEN VOLUME END) AS [12]
,MAX(CASE WHEN HOURS = 13 THEN VOLUME END) AS [13]
FROM #TEMP
;
最好用字母字符标记整数/数字,而不是依赖于括号。这种方法适用于任何平台。
SELECT
MAX(CASE WHEN HOURS = 8 THEN VOLUME END) AS COL_8
,MAX(CASE WHEN HOURS = 9 THEN VOLUME END) AS COL_9
,MAX(CASE WHEN HOURS = 10 THEN VOLUME END) AS COL_10
,MAX(CASE WHEN HOURS = 11 THEN VOLUME END) AS COL_11
,MAX(CASE WHEN HOURS = 12 THEN VOLUME END) AS COL_12
,MAX(CASE WHEN HOURS = 13 THEN VOLUME END) AS COL_13
FROM #TEMP
;
答案 2 :(得分:0)
除了ID列之外,使用数据透视查询总是好的,为了简化你可以这样得到结果集
WITH cte
AS (
SELECT *
FROM #TEMP
PIVOT(max(volume) FOR [DialHour] IN (
"8"
,"9"
,"10"
,"11"
,"12"
,"13"
,"14"
,"15"
,"16"
,"17"
,"18"
,"19"
)) AS pvt
)
SELECT 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19...
FROM cte
答案 3 :(得分:0)
这假设您正在使用 SQL Server ,那么使用动态 PIVOT 方法总是更好
declare @col nvarchar(max), @query nvarchar(max)
select @col = stuff(
(select ','+quotename(Hours) from #tm for xml path('')),
1,1, '')
set @query = N'select * from
(
select * from #tm
)a
PIVOT
(
MAX(Volume) for Hours in ('+@col+')
)pvt'
EXECUTE sp_executesql @query
结果:
8 9 10 11 12 13
1000 1012 1045 1598 1145 1147