Reputation: 2577
I'm using This to get pivot results for a table. But I want the resulting columns and rows both in a specific order. So the rows would be sorted by CDATE
and the columns would be CDATE
, BALANCE
, then the DATE
columns.
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
Upvotes: 2
Views: 147
Reputation: 37348
I edited the answer in the link you provided in your question to achieve the ordering issue. Just add ORDER BY
clause to your dynamic query:
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
OR You can use common table expression to achieve this. like the following:
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
Upvotes: 2