0

如何按列显示日期

表格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 查询来做到这一点?

4

1 回答 1

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')
于 2012-05-12T11:04:45.577 回答