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
 how to get row data as coulmn using Pivot

Author  Topic 

mohan123
Constraint Violating Yak Guru

252 Posts

Posted - 2013-01-16 : 09:02:57
hello all,

i have table in which i need to get data year wise like 2009,2010,2011,2012

i written this query

SELECT UserCN,LastName,FirstName,Gender,DOB,TotalPointsCoeff,Level FROM EXCZ_WellcentPointTotal ew
join USR_Demographics ud ON ew.UserID=ud.UserID
WHERE ew.UserID IN
(
SELECT DISTINCT ud.UserID FROM USR_Demographics ud
join EXCZ_measurements lu on ud.UserID=lu.UserID
WHERE ud.CustId=277 AND year(entryDate)=2009

INTERSECT

SELECT DISTINCT ud.UserID FROM USR_Demographics ud
join EXCZ_measurements lu on ud.UserID=lu.UserID
WHERE ud.CustId=277 AND year(entryDate)=2010

it is showing in column wise...

again i used pivot to get rquired result

select UserCN,LastName,FirstName,Gender,DOB,TotalPointsCoeff,Level from
(

select Year(entryDate) as pivot_col FROM EXCZ_WellcentPointTotal ew

INNER JOIN USR_Demographics as o ON (ew.UserID=o.UserID)
join EXCZ_measurements lu on o.UserID=lu.UserID
WHERE o.CustId=277
) as t
pivot
(
COUNT(entryDate for pivot_col in ([2009],[2010],[2011],[2012])
) as p

it not showing any result

how to do this one??

P.V.P.MOhan

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-01-16 : 09:37:00
[code]
select Year(entryDate) as pivot_col, EntryDate FROM EXCZ_WellcentPointTotal ew

INNER JOIN USR_Demographics as o ON (ew.UserID=o.UserID)
join EXCZ_measurements lu on o.UserID=lu.UserID
WHERE o.CustId=277
) as t
pivot
(
COUNT(entryDate) for pivot_col in ([2009],[2010],[2011],[2012])
) as p
[/code]

--
Chandu
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2013-01-17 : 05:02:13
For unknown number of years, use this
http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -