Link to home
Start Free TrialLog in
Avatar of mmalik15
mmalik15

asked on

how to write a Pivot table style SQL Query in this scenario

I  have the following tables in my database
PerformanceObjectives(PerObjID,Title,etc)
Modules(ModuleID,Title)
ObjectiveModules(PerObjID,ModuleID)
Subjects(SubjectID,Title)
ModuleSubjects(ModuleID,SubjectID)
EmployeeTrainingHours(TrainingHoursID,EmployeeID,StartDate,EndDate,SubjectID,NoOfHours)
Employee(EmployeeID,Firstname,Surname,etc).

I want my query to return the results like this

                Module1    Module2     Module3    Total
Emp1       10                5                    5           20
Emp2       5                  7                  12           24
Emp3       2                  3                   9            14

Now the Modules (Module1,Module2,Module3) values represent the sum of the hours of the subjects present in that module. e.g. Module1 may have sub1,sub2 and sub3. and the sum of hours spent on these subjects is 10. Similary each cell represent the total no of hours spent on each module. I am using SQL server 2005 and also taking some help from this post

https://www.experts-exchange.com/questions/23880880/how-to-get-a-timetable-like-layout-using-c.html

but unfortunately could not figure out

 I will be very thankfull for any help.








ASKER CERTIFIED SOLUTION
Avatar of frankytee
frankytee
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Raja Jegan R
This will solve your requirement:
since this is using a pivot table, your query performance will be better.
SELECT EmployeeID, ModuleID, Module1, Module2, Module3
FROM (
SELECT EM.EmployeeID, MS.ModuleID, SUM(ET.NoOfHours) TotalNoofHours
FROM Employee EM, EmployeeTrainingHours ET, ModuleSubjects MS
WHERE EM.EmployeeID = ET.EmployeeID
  AND ET.SubjectID = MS.SubjectID
GROUP BY EM.EmployeeID, MS.ModuleID) ps
PIVOT
(
max(TotalNoofHours) FOR ModuleID IN (Module1, Module2, Module3)) AS pvt

Open in new window