SQL Server按类别列出

时间:2012-09-21 09:10:20

标签: sql sql-server sql-server-2000

如果我有一个存储余额行的表

    Code     cat  balance
    ----------------------
    Sales    101  123
    Cost     101   45
    Overhead 101   67
    Sales    102  890
    Costs    102   12
    Overhead 102   34

(等等,假设'cat'是产品类别,还有更多类别,'代码'代表总帐代码)

我如何编码以便输出显示....

Code   101   102   [103..etc ->]
-----------------------------------    
Sales  123   890   [#]
Costs   45    12   [#]
Overhead...

这可能很简单,但我找不到这样做的方法,我们将非常感谢任何帮助。

的Darren

3 个答案:

答案 0 :(得分:3)

不幸的是,SQL Server 2000没有PIVOT函数,但您可以使用动态SQL复制它。

DECLARE @query  AS NVARCHAR(MAX),  -- VARCHAR(8000)  in SQL Server 2000 or text
  @rowCount as int,
  @pivotCount as int,
  @pivotRow as varchar(10) = ''

select distinct cat
into #colsPivot
from yourtable

set @pivotCount= (select COUNT(*) from #colsPivot) 
set @rowCount = 1
set @query = ''

---- create the CASE string
while @rowCount <= @pivotCount
    begin
        set @pivotRow = (select Top 1 cat from #colsPivot)

        set @query = @query + ', sum(case when cat = ' + @pivotRow + ' then balance end) as ''' + @pivotRow + ''''

        delete from #colsPivot where cat = @pivotRow

        if @rowCount <= @pivotCount
            begin
                set @rowCount = @rowCount + 1
                print @rowCount
            end
    end

-- add the rest of the SQL Statement
set @query = 'SELECT code ' + @query + ' from yourtable group by code'

exec(@query)

drop table #colsPivot

请参阅SQL Fiddle With Demo

答案 1 :(得分:1)

select 
    Code,
    sum(case cat when 101 then balance else 0) as '101',
    sum(case cat when 102 then balance else 0) as '102'
from balances
group by Code

答案 2 :(得分:0)

尝试使用sql server的PIVOT功能