2016-11-29 84 views

回答

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 
相關問題