I have spent hours on even this one SQL pivot.
I would like to master SQL pivots or at least get much better with them.
I got one unpivot to work here a while back:
I have right now, this super fast query.
Column one shows me all the machines.
Column two shows all the operators
The next 12 columns show me all the numbers want to know.
The very fast query is like:
select Line,
Operator,
isnull( sum(Outfeeed*1.0)/ nullif(sum(standardVol),0) as eff
--(11 more math selects)
where t_stamp between DATEADD(month, -6, CAST(GETDATE() AS date))
and DATEADD(minute, -1,cast(GETDATE()as datetime ))
and Operator is not null
and Operator i!=' '
group by Operator, Line
Then I spent hours trying to pivot the data.
I sort of got it working.
select Operator, Line1, Line2, LineN from(
select Line,
Operator,
isnull( sum(Outfeeed*1.0)/ nullif(sum(standardVol),0) as eff
where t_stamp between DATEADD(month, -6, CAST(GETDATE() AS date))
and DATEADD(minute, -1,cast(GETDATE()as datetime ))
and Operator is not null
and Operator i!=' '
group by Operator, Line
) as src
pivot ( max(eff) for Line in (Line1, Line2, LineN) as pvt
Only gives me one of the values.
Required me to use a windowed function for the pivot.
I went with max, though I hope it is one to one as my testing appears to be.
I want to make a totals column, that I hope not to have to self join to get.
I want to get more columns too.