如何对SQL Server 2008数据透视结果列和行进行排序?

时间:2016-11-29 21:31:05

标签: sql-server sql-server-2008 tsql pivot

我使用This来获取表格的透视结果。但我希望得到的列和行都按特定的顺序排列。因此,行将按CDATE排序,列将为CDATEBALANCE,然后是DATE列。

CDATE      | BALANCE | 04-2007 | 05-2007 | 06-2007 | TRANS TOT
2003-01-15 | 5000    | 60      | 0       | 0       | 60 
2003-02-15 | 4000    | 40      | 0       | 0       | 40
2003-03-15 | 5500    | 20      | 15      | 15      | 50 

1 个答案:

答案 0 :(得分:2)

我在您提问中提供的链接中编辑了答案,以实现订购问题。只需在动态查询中添加ORDER BY子句:

create table temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('3/1/2012', 'ABC', 1100.00)


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p  ORDER BY date, ' + @cols 


Execute(@query)

drop table temp

或者您可以使用common table expression来实现此目的。如下:

set @query = 'WITH CTE_1(date, ' + @cols + ') AS (SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p ) SELECT * FROM CTE_1 ORDER BY date, ' + @cols