尝试这个
DECLARE @cols NVARCHAR(2000)
DECLARE @query NVARCHAR(4000)
SELECT @cols = STUFF(( SELECT DISTINCT
'],[' + `Date`
FROM Table1
ORDER BY '],[' + `Date` FOR XML PATH('')
), 1, 2, '') + ']';
SET @query = N'SELECT ID, '+
@cols +'
FROM
(SELECT ID
FROM Table1
PIVOT
(
SUM([`Value`])
FOR `Date` IN
( '+
@cols +' )
) AS pvt
ORDER BY ID;'
EXECUTE(@query)
SQL2000版
DECLARE @date Date,@sql nvarchar(MAX)
DECLARE date_cursor CURSOR
FOR SELECT DISTINCT [Date] FROM table_one ORDER BY [Date]
SET @sql = ''
OPEN date_cursor
FETCH NEXT FROM date_cursor INTO @date
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = @sql+ ',MAX(CASE CONVERT(nvarchar(10),[Date],103) WHEN '''+CONVERT(nvarchar(10),@date,103)+''' THEN [Value] END) AS ['+CONVERT(nvarchar(10),@date,103)+']'
FETCH NEXT FROM date_cursor INTO @date
END
CLOSE date_cursor
DEALLOCATE date_cursor
EXEC('SELECT ID'+@sql+' FROM table_one GROUP BY ID')
或者
DECLARE @loop int,@date Date,@sql nvarchar(4000)
DECLARE @TempTable TABLE
(
[Date] DATE
)
INSERT INTO @TempTable SELECT DISTINCT [Date] FROM table1 ORDER BY [Date]
SET @sql = ''
SET @loop = 1
WHILE (@loop<=31)
BEGIN
IF EXISTS(SELECT * FROM @TempTable WHERE DAY([Date])=@loop)
BEGIN
SET @date = (SELECT [Date] FROM @TempTable WHERE DAY([Date])=@loop)
SET @sql = @sql+ ',MAX(CASE CONVERT(nvarchar(10),[Date],103) WHEN '''+CONVERT(nvarchar(10),@date,103)+''' THEN [Value] END) AS [DATE'+CONVERT(nvarchar(2),@loop)+']'
END
ELSE
SET @sql = @sql+ ', NULL AS [DATE'+CONVERT(nvarchar(2),@loop)+']'
SET @loop = @loop+1
END
EXEC('SELECT ID'+@sql+' FROM table1 GROUP BY ID')