日期:2014-05-18 浏览次数:20535 次
SELECT * INTO #TRanen FROM ( SELECT 1 AS ID, CONVERT(DATETIME,'2012-1-11') AS mmTime,12 as [NO] UNION ALL SELECT 2, '2012-1-11',4 UNION ALL SELECT 3, '2012-1-15',27 UNION ALL SELECT 4, '2012-1-16',8 ) T DECLARE @SQL VARCHAR(500) SELECT @SQL = ISNULL(@SQL + ',' ,'') + '[' + CONVERT(NVARCHAR(10),MMTIME,23)+']' FROM #TRanen GROUP BY CONVERT(NVARCHAR(10),MMTIME,23) EXEC(' SELECT * FROM #TRanen A PIVOT (SUM([NO]) FOR MMTIME IN('+@SQL+')) B ') DROP TABLE #TRanen
------解决方案--------------------
IF OBJECT_ID(N'tempdb..#TRanen') IS NOT NULL DROP TABLE #TRanen GO SELECT * INTO #TRanen FROM ( SELECT 1 AS ID, CONVERT(DATETIME,'2012-1-11') AS mmTime,12 as [NO] UNION ALL SELECT 2, '2012-1-11',4 UNION ALL SELECT 3, '2012-1-15',27 UNION ALL SELECT 4, '2012-1-16',8 ) T GO DECLARE @SQL VARCHAR(500) SELECT @SQL = ISNULL(@SQL + ',' ,'') + QUOTENAME(CONVERT(VARCHAR(10),MMTIME,120)) FROM (SELECT DISTINCT MMTIME = CONVERT(NVARCHAR(10),MMTIME,120) FROM #TRanen) AA EXEC(' SELECT ID,'+@SQL+' FROM #TRanen A PIVOT (SUM([NO]) FOR MMTIME IN('+@SQL+')) B ') DROP TABLE #TRanen /* ID 2012-01-11 2012-01-15 2012-01-16 1 12 NULL NULL 2 4 NULL NULL 3 NULL 27 NULL 4 NULL NULL 8 */