--Sql Server 2014 Express Edition
--Batches are separated by 'go'
--DATA
CREATE TABLE #T (ChildName nvarchar(50), DATE nvarchar(50), CLASS int, [SERVING TIME] nvarchar(50))
INSERT INTO #T (ChildName, DATE , CLASS , [SERVING TIME])
VALUES ('Andrew', '20.11.2019' , 1 , 'Breakfast,Lunch,Snacks'),
('Andrew', '21.11.2019' , 1 , 'Breakfast,Lunch'),
('David', NULL , 1 , NULL) ,
('Ijas' , '22.11.2019' , 1 , 'Snacks' ) ,
('Kerry', NULL , 1 , NULL ) ,
('Paul' , NULL , 1 , NULL ),
('Ram' , '22.11.2019' , 1 , 'Snacks'),
('Ram' , '23.11.2019' , 1 , 'Lunch' )
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
--PIVOT
SELECT @cols = CASE WHEN @cols IS NULL THEN C
ELSE @cols +',' + C
END
FROM (SELECT DISTINCT '[' + DATE + ']' as C FROM #T WHERE DATE IS NOT NULL)t;
SELECT @query = N'
SELECT ChildName,'+@cols+N' , CLASS
FROM
(SELECT ChildName, DATE , CLASS , [SERVING TIME] FROM #T) AS SourceTable
PIVOT
(
MAX([SERVING TIME])
FOR DATE IN ('+@cols+N')
) AS PivotTable
ORDER BY ChildName
;'
--debug
PRINT @query
EXEC Sp_EXECUTESQL @query
DROP TABLE #T
GO
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。