我已经尽力理解如何在SQL中创建数据透视表,但是我无法对其进行管理!
我有以下几列:
link_id route_section date_1 StartHour AvJT data_source ....... ............. ....... ........... ...... ............
拥有60万行数据。
我在下面的数据透视表中需要它们;
date_1
link_id
AvJT
data_source
数据透视表
Link_ID date_1 StartHour 00001a 000002a 000003a 000004a 20/01/2014 8 456 4657 556 46576 21/01/2014 8 511 4725 601 52154 22/01/2014 8 468 4587 458 47585 23/01/2014 8 456 4657 556 46576 24/01/2014 8 456 4657 556 46576 25/01/2014 8 456 4657 556 46576 26/01/2014 8 456 4657 556 46576
我设法获得了以下代码,该方法有效,但仅给我date_1作为列标题,而不给我StartHour,或者将filter作为date_source =‘1’。
Use [C1_20132014] DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) DECLARE @ColumnName AS NVARCHAR(MAX) --Get distinct values of the PIVOT Column SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(Link_ID) FROM (SELECT DISTINCT Link_ID FROM C1_May_Routes) AS Link_ID --Prepare the PIVOT query using the dynamic SET @DynamicPivotQuery = N'SELECT Date_1, ' + @ColumnName + ' FROM C1_May_Routes PIVOT(SUM(AvJT) FOR Link_ID IN (' + @ColumnName + ')) AS PVTTable' --Execute the Dynamic Pivot Query EXEC sp_executesql @DynamicPivotQuery
谢谢你的帮助,
亨利
在这里,您将选择一列中的值以在数据透视图中显示为一列
DECLARE @cols NVARCHAR (MAX) SELECT @cols = COALESCE (@cols + ',[' + AvJT + ']', '[' + AvJT + ']') FROM (SELECT DISTINCT AvJT FROM YourTable) PV ORDER BY AvJT
现在旋转查询
DECLARE @query NVARCHAR(MAX) SET @query = 'SELECT * FROM ( SELECT date_1, StartHour,AvJT, data_source FROM YourTable ) x PIVOT ( -- Values in each dynamic column SUM(data_source) FOR AvJT IN (' + @cols + ') ) p;' EXEC SP_EXECUTESQL @query
如果要对列名称不是动态的地方执行此操作,则可以执行以下查询
SELECT DATE_1,STARTHOUR, MIN(CASE WHEN AvJT='00001a' THEN data_source END) [00001a], MIN(CASE WHEN AvJT='00002a' THEN data_source END) [00002a], MIN(CASE WHEN AvJT='00003a' THEN data_source END) [00003a], MIN(CASE WHEN AvJT='00004a' THEN data_source END) [00004a] FROM YOURTABLE GROUP BY DATE_1,STARTHOUR
编辑 :
我正在为您更新的问题进行更新。
声明一个变量进行过滤 data_source
DECLARE @DATASOURCE VARCHAR(20) = '1'
代替QUOTENAME,您可以使用另一种格式来获取数据透视表的列
QUOTENAME
DECLARE @cols NVARCHAR (MAX) SELECT @cols = COALESCE (@cols + ',[' + Link_ID + ']', '[' + Link_ID + ']') FROM (SELECT DISTINCT Link_ID FROM C1_May_Routes WHERE data_source=@DATASOURCE) PV ORDER BY Link_ID
现在枢纽
DECLARE @query NVARCHAR(MAX) SET @query = 'SELECT * FROM ( -- We will select the data that has to be shown for pivoting -- with filtered data_source SELECT date_1, StartHour,AvJT, Link_ID FROM C1_May_Routes WHERE data_source = '+@DATASOURCE+' ) x PIVOT ( -- Values in each dynamic column SUM(AvJT) -- Select columns from @cols FOR Link_ID IN (' + @cols + ') ) p;' EXEC SP_EXECUTESQL @query