如何按列显示日期
表1
ID Date Value
001 01/01/2012 100
001 02/01/2012 200
...
...
001 31/01/2012 250
002 01/01/2012 050
002 02/01/2012 100
...
002 31/01/2012 075
....
我希望按ID riw
按日期显示行组显示值预期输出
ID 01/01/2012 02/01/2012 ... 31/01/2012
001 100 200 .... 250
002 050 100 .... 075
.....
如何使用SQL查询执行此操作?
答案 0 :(得分:1)
试试这个
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')