Reputation: 531
If I have a table that stores lines of balances
Code cat balance
----------------------
Sales 101 123
Cost 101 45
Overhead 101 67
Sales 102 890
Costs 102 12
Overhead 102 34
(etc, assuming that the 'cat' is a product category and there are many more categories and that 'code' represents a general ledger code)
How would I code it so that the output shows....
Code 101 102 [103..etc ->]
-----------------------------------
Sales 123 890 [#]
Costs 45 12 [#]
Overhead...
This is probably very simple but I cant find a way of doing this and any help would be greatly appreciated.
Darren
Upvotes: 2
Views: 182
Reputation: 247840
Unfortunately, SQL Server 2000 does not have a PIVOT
function but you can replicate it using dynamic 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
Upvotes: 3
Reputation: 125444
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
Upvotes: 1