How to convert row to columns?

半世苍凉 提交于 2019-12-04 22:29:19

Try this, it works in SQL Server 2008:

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

SELECT @cols = STUFF((SELECT ',' + PROJECT
                    FROM (SELECT DISTINCT PROJECT FROM Table1 )sub
                   FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


SET @query = 'SELECT * FROM
                (
                SELECT CATEGORY_ID, PROJECT, AMOUNT 
                FROM Table1   
                --WHERE VOUCHER_DATE BETWEEN '' AND ''
                ) AS T1
                PIVOT (SUM(AMOUNT) FOR PROJECT IN ('+@cols+')) AS T2

'
EXEC(@query)

SQL Fiddle

Basically, you use dynamic SQL to set the list of projects since it can vary, then PIVOT as per usual, I commented out the voucher date criteria because the sample dates weren't in proper format. If some projects are excluded entirely by the date requirement, then you will also add the date criteria to the top portion that sets the project list.

If the number of values for project column are known and they are also few you can try this:

select category_id
    ,sum(case when project='pnr' then amount else 0. end) as pnr
    ,sum(case when project='npk' then amount else 0. end) as npk
    ,sum(case when project='jpg' then amount else 0. end) as jpg
from [yourtable]
where [voucher date] between @bd and @ed--@bd and @ed are the input interval
group by category_id

or to play with pivot command

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!