Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Pivot

Author  Topic 

gavakie
Posting Yak Master

221 Posts

Posted - 2010-08-18 : 15:50:46
I have this table I need to pivot on

Select Region, Market, fiscal_mnth, fiscal_yr,
sales_grp, sup_name, mgr_name, emp_name,
Salesrep_ocr, mnth_name,
sales_group, daysinmonth, daysreported, TYPE
From #Pivot

these would be across the top
dte,
day_name

These would be the data

Help!


dte, dte, dte, dte,
columns b1 b1 b1 b1
columns b1 b1 b1 b1
columns b1 b1 b1 b1

MSquared
Yak Posting Veteran

52 Posts

Posted - 2010-08-18 : 16:52:22
Here's a script that will create a pivot table dynamically. You can modify it for your needs.


create table #t1 (name varchar(20), Address varchar(20), ClaimNumber int, Phone varchar(20))
create table #t2 (ClaimNumber int, ClaimCode smallint)

insert into #t1
select 'Joe', '1234 Road',1, '111-1111' union all
select 'Sue', '456 Road',2, '222-2222' union all
select 'Mike', '78 Street',3, '333-3333' union all
select 'Jim', '1 Main',4, '444-4444'

insert into #t2
select 1, 21 union all
select 1, 23 union all
select 1, 54 union all
select 1, 26 union all
select 1, 83 union all
select 2, 27 union all
select 2, 30 union all
select 3, 54


--PIVOT
DECLARE @Colslist VARCHAR(MAX)
DECLARE @Cols TABLE (Head VARCHAR(MAX))

INSERT @Cols (Head)
SELECT DISTINCT ClaimCode
FROM #t2

SELECT @ColsList = COALESCE(@ColsList + ',[', '[') + Head + ']'
FROM @Cols t

EXEC ('SELECT *
FROM
(
SELECT a.name, a.Address, a.ClaimNumber, a.Phone, ClaimCode
FROM #t1 a inner join #t2 b
on a.ClaimNumber = b.ClaimNumber
) t
PIVOT (avg(ClaimCode) FOR ClaimCode IN (' + @ColsList + ')) PVT')



For Faster results please follow the posting guidelines here

http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-19 : 13:32:42
see

http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -