2

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

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

(等等,假设'cat'是一个产品类别并且有更多类别并且'code'代表一个总帐代码)

我将如何对其进行编码以便输出显示....

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

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

达伦

4

3 回答 3

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

于 2012-09-21T13:18:04.147 回答
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
于 2012-09-21T13:07:13.537 回答
0

尝试使用 sql server 的 PIVOT 功能

于 2012-09-21T09:11:28.557 回答