tsql中同一列上的多个枢轴

时间:2019-06-11 11:19:55

标签: sql-server tsql pivot

如何在tsql的同一列上定义透视?

例如:

 SELECT * FROM (
 SELECT CAST(start_time AS DATE) AS [Date],
 DATEPART(hour,start_time) AS [Hour], 
 Count(is_sale)AS  [Sales Count] 
 ,Count(is_not_sale)AS  [No Sales Count] 
 FROM  prov_sales WITH(NOLOCK)
 GROUP BY CAST(start_time AS DATE), DATEPART(hour,start_time)) AS HourlySalesData

 PIVOT( SUM([Sales Count]) FOR [Hour] IN ([0], [1], [2], [3], [4], [5], [6], [7],
     [8], [9], [10],[11], [12], [13], [14], [15], [16], 
     [17], [18], [19], [20], [21], [22], [23])) AS DatePivot1

 PIVOT( SUM([No Sales Count]) FOR [Hour] IN ([0], [1], [2], [3], [4], [5], [6], [7],
     [8], [9], [10],[11], [12], [13], [14], [15], [16], 
     [17], [18], [19], [20], [21], [22], [23])) AS DatePivot2

我上面的tsql无法正常工作,因为小时列出现错误,该列具有从[1]到[23]的重复值。

1 个答案:

答案 0 :(得分:1)

由于PIVOT从IN列表创建列名,因此无法两次定义相同的列,如[1]。尽管以下解决方案不是标准解决方案,但可以满足您的目的-

SELECT * FROM (
SELECT CAST(start_time AS DATE) AS [Date],
--Created the hour column twice for Pivoting twice
'Sales_' + CAST(DATEPART(hour,start_time) AS VARCHAR) AS [Hour_Sales], 
'NoSales_' + CAST(DATEPART(hour,start_time) AS VARCHAR) AS [Hour_NoSales], 
Count(is_sale)AS  [Sales Count] 
,Count(is_not_sale)AS  [No Sales Count] 
FROM  prov_sales WITH(NOLOCK)
GROUP BY CAST(start_time AS DATE), DATEPART(hour,start_time)) AS HourlySalesData

PIVOT( SUM([Sales Count]) FOR [Hour_Sales] IN ([Sales_0], [Sales_1], [Sales_2], [Sales_3], [Sales_4], [Sales_5], [Sales_6], [Sales_7],
     [Sales_8], [Sales_9], [Sales_10],[Sales_11], [Sales_12], [Sales_13], [Sales_14], [Sales_15], [Sales_16], 
     [Sales_17], [Sales_18], [Sales_19], [Sales_20], [Sales_21], [Sales_22], [Sales_23])) AS DatePivot1

PIVOT( SUM([No Sales Count]) FOR [Hour_NoSales] IN ([NoSales_0], [NoSales_1], [NoSales_2], [NoSales_3], [NoSales_4], [NoSales_5], [NoSales_6], [NoSales_7],
     [NoSales_8], [NoSales_9], [NoSales_10],[NoSales_11], [NoSales_12], [NoSales_13], [NoSales_14], [NoSales_15], [NoSales_16], 
     [NoSales_17], [NoSales_18], [NoSales_19], [NoSales_20], [NoSales_21], [NoSales_22], [NoSales_23])) AS DatePivot2