0

我有下表:

  PROCESS ID       VOUCHER DATE     CATEGORY_ID     PROJECT     AMOUNT
  -----------      ------------    ------------     -------     -------
  1001             12/03/13         Miscellaneous   pnr         1000
  1001             12/03/13         Miscellaneous   pjk         2000
  1002             20/07/13         Local Travel    pnr         3000
  1002             20/07/13         Local Travel    npk         3400
  1003             29/09/14         Miscellaneous   jpg         1000
  1004             23/10/13         Local Travel    pnr         2000
  1005             24/10/13         Miscellaneous   pnr         1000
  1005             24/10/13         Local Travel    pnr         1000

在界面中,我将提供介于某个日期之间的VOUCHER DATE,例如20/01/1327/10/13,我必须得到如下格式的输出:

  CATEGORY_ID       pnr         npk         jpg
  -----------      -----       -----       -----      
  Miscellaneous    1000         0           1000
  Local Travel     6000         3400        0

项目是动态的,它可以变化。

4

2 回答 2

1

试试这个,它适用于 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小提琴

基本上,您使用动态 SQL 来设置项目列表,因为它可能会有所不同,然后像往常一样 PIVOT,我注释掉了凭证日期标准,因为示例日期的格式不正确。如果某些项目完全被日期要求排除在外,那么您还将日期标准添加到设置项目列表的顶部。

于 2013-06-15T20:32:50.827 回答
0

如果项目列的值的数量已知并且它们也很少,您可以尝试以下操作:

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

或玩枢轴命令

谢谢

于 2013-06-15T20:07:28.717 回答