我有一个数据集如下:
HID HDate Comments
60038A 1/5/2018 5:39:48 TEST
60038A 1/6/2018 9:02:03 sample
60038A 1/8/2018 9:23:27 another test
60038A 1/6/2018 10:33:00 delayed数据集告诉我们,对于某些ID列,现在保存日期方面的注释,我想要的是,date列应该显示为列和它们各自的注释。
我编写了相同的数据透视查询,如下所示:
DECLARE @QUERY NVARCHAR(MAX), @Soucecolumn VARCHAR(MAX)
SET @Soucecolumn = STUFF((SELECT distinct ',[' + Convert(varchar,[HDate],120) + ']' FROM TRCK_Comments FOR XML PATH('')),1,1,'')
SET @QUERY = 'SELECT HID, ' + @Soucecolumn + ' FROM TRCK_Comments PIVOT (MAX(Comments) FOR [HDate] IN (' + @Soucecolumn + ')) AS pvt'
exec sp_executesql @QUERY但是上面的查询为我提供了具有相同ID的多行的结果,使用NULL值的结果,我希望单行相同的ID与该特定日期列中可用的注释相同,
Actual result that i am getting
HID 2018-01-04 11:26:05 2018-01-04 11:26:16 2018-01-04 11:26:27 2018-01-04 18:26:46
1 this is sample comment NULL NULL NULL
1 NULL this is comment NULL NULL
2 NULL NULL this is sample NULL
2 NULL NULL NULL nfdjfdfddf预期结果
HID 2018-01-04 11:26:05 2018-01-04 11:26:16 2018-01-04 11:26:27 2018-01-04 18:26:46
1 this is sample comment this is comment NULL NULL
2 NULL NULL this is sample nfdjfdfddf这是我的实际数据集
ID HID HDate Comments
1 1 2018-01-04 11:26:05 this is sample comment
2 1 2018-01-04 11:26:16 this is sample comment this is sample comment
3 2 2018-01-04 11:26:27 this is sample comment this is sample comment this is sample comment
4 2 2018-01-04 18:26:46 nfdjfdfddf想按HID进行分组(而不是标识类型的ID )
发布于 2018-01-08 07:15:27
在您提供的样本数据中:
CREATE TABLE #DataSource
(
[ID] TINYINT
,[HID] VARCHAR(12)
,[HDate] DATETIME2
,[Comments] VARCHAR(128)
);
INSERT INTO #DataSource ([ID], [HID], [HDate], [Comments])
VALUES ('1', '1', '2018-01-04 11:26:05', 'this is sample comment')
,('2', '1', '2018-01-04 11:26:16', 'this is sample comment this is sample comment')
,('3', '2', '2018-01-04 11:26:27', 'this is sample comment this is sample comment this is sample comment')
,('4', '2', '2018-01-04 18:26:46', 'nfdjfdfddf');
DECLARE @DynammicTSQLStatement NVARCHAR(MAX)
,@DynamicPIVOTColumns NVARCHAR(MAX);
SET @DynamicPIVOTColumns = STUFF
(
(
SELECT ',[' + CONVERT(VARCHAR(19), [HDate], 120) + ']'
FROM #DataSource
GROUP BY [HDate]
ORDER BY [HDate]
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET @DynammicTSQLStatement = N'
SELECT *
FROM
(
SELECT [HID], [HDate], [Comments]
FROM #DataSource
) DS
PIVOT
(
MAX([Comments]) FOR [HDate] IN (' + @DynamicPIVOTColumns + ')
) PVT';
EXEC sp_executesql @DynammicTSQLStatement;
DROP TABLE #DataSource;

https://stackoverflow.com/questions/48145659
复制相似问题