Question

I think what I need here is to create a pivot table. I can do it without having the laborhours column, but when I try to create it with the laborhours column it doesn't work.

Would you please show me how to get the results I am asking for?

There are multiple more "Par" values, which are not shown below.

Here is my table:

WorkDate    Par QTY laborhrs
03/14/14    CR  100 0.67
03/25/14    ET  100 0.73
03/05/14    CR  50  0.37
03/13/14    ER  50  0.72
03/04/14    YD  400 1.68
03/25/14    CR  200 0.8
03/25/14    CR  300 1.5

Here is what I would like:

WorkDate    CR  CRHours ER  ERHours ET  ETHours YD  YDHours
03/04/14    0   0       0   0       0   0       400 1.68
03/05/14    50  0.37    0   0       0   0       0   0
03/13/14    0   0       50  0.72    0   0       0   0
03/14/14    100 0.67    0   0       0   0       0   0
03/25/14    500 2.3     0   0       100 0.73    0   0

The new "Hours" columns are from the laborhrs column per each "par"

Was it helpful?

Solution

There are multiple approaches You could create two PIVOT Subqueries and join them but I prefer this way

SELECT
t.WorkDate
,SUM(CASE WHEN t.Par='CR' THEN t.Qty ELSE 0 END) AS CR
,SUM(CASE WHEN t.Par='CR' THEN t.laborhrs ELSE 0 END) AS CRHours

,SUM(CASE WHEN t.Par='ER' THEN t.Qty ELSE 0 END) AS ER
,SUM(CASE WHEN t.Par='ER' THEN t.laborhrs ELSE 0 END) AS ERHours

,SUM(CASE WHEN t.Par='ET' THEN t.Qty ELSE 0 END) AS ET
,SUM(CASE WHEN t.Par='ET' THEN t.laborhrs ELSE 0 END) AS ETHours

,SUM(CASE WHEN t.Par='YD' THEN t.Qty ELSE 0 END) AS YD
,SUM(CASE WHEN t.Par='YD' THEN t.laborhrs ELSE 0 END) AS YDHours

GROUP BY t.WorkDate
FROM [tablename] t

It's the fastest approach to these problems that I've found as it just needs to traverse the table once.

OTHER TIPS

another option is correlated queries:

select workdate,
(select sum(qty) from labour a where a.workdate=b.workdate and a.par='CR') CR,
(select sum(laborhrs) from labour a where a.workdate=b.workdate and a.par='CR') CRhours,
(select sum(qty) from labour a where a.workdate=b.workdate and a.par='ER') ER,
(select sum(laborhrs) from labour a where a.workdate=b.workdate and a.par='ER') ERhours,
(select sum(qty) from labour a where a.workdate=b.workdate and a.par='ET') ET,
(select sum(laborhrs) from labour a where a.workdate=b.workdate and a.par='ET') EThours,
(select sum(qty) from labour a where a.workdate=b.workdate and a.par='YD') YD,
(select sum(laborhrs) from labour a where a.workdate=b.workdate and a.par='YD') YDhours
from yourtable b
group by workdate
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top