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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 need help with pivot query

Author  Topic 

rama108
Posting Yak Master

115 Posts

Posted - 2012-04-20 : 15:25:47
Hello All,
I have the query as follows:

SELECT d.Id, d.Name, ISNULL(AVG(ev.marks),0) marks, es.timePeriod, ISNULL(SUM(es.amount),0) Amount
FROM depts d INNER JOIN
Employees e ON d.Id = e.deptId INNER JOIN
EmployeeScales ee ON e.Id = ee.EmployeeId INNER JOIN
scales ev ON ee.scaleId = ev.Id
inner join scaleMatrix es on ev.MatrixId = es.Id
group by d.Id, d.Name,es.timePeriod
order by d.Name,es.timePeriod

The results are as follows:

ID Name Marks timePeriod Amount

44 Business 3.173559 1 42.31000
44 Business 3.173559 2 53.76000
44 Business 3.173559 3 68.06000
44 Business 3.173559 4 96.18000
44 Business 3.173559 5 107.88000
44 Business 3.173559 6 112.08000
44 Business 3.173559 7 127.63000
44 Business 3.173559 8 140.46000
44 Business 3.173559 9 151.18000
44 Business 3.173559 10 138.89000
44 Business 3.173559 11 109.37000
44 Business 3.173559 12 78.64000

What I need to do is to have id, name, marks, timeperiods and amounts in one record as follows:

44 Business 3.172559 1 2 3 4 5 6 7 8 9 10 11 12 followed by the values of each amount

Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-04-20 : 15:29:54
have a look at this

http://beyondrelational.com/modules/2/blogs/70/posts/10791/dynamic-crosstab-with-multiple-pivot-columns.aspx

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

Go to Top of Page

rama108
Posting Yak Master

115 Posts

Posted - 2012-04-20 : 16:07:03
I created a variable table and inserted all record in it. Then I used pivot to spread it out across. Problem resolved.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-04-21 : 13:14:57
cool

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

Go to Top of Page
   

- Advertisement -