Hi I have this data returning from a query:Procedure Intermediate New Old Total avg Proc1 6 0 0 6 2.000000 Proc2 74 13 0 87 29.000000 Proc3 29 0 0 29 9.666666 Proc4 16 0 0 16 5.333333
And I want to dynamically calculate the average rather than divide the total by the number of columns every time, I want to divide only by the number of non zero values per row for intermediate, new and old. So row 1 average would just be itself = 6, row 2 would be 74+13+87/3 etc.;with cte as( select f.Procedure, SUM(case when f.old_new = 'O' then f.Value else 0 end) "Intermediate", SUM(case when f.old_new = 'Y' then f.Value else 0 end) "New", SUM(case when f.old_new = 'N' then f.Value else 0 end) "Old" from MyTable f group by f.Procedure)select cte.Procedure, cte.[Old], cte.[Intermediate], cte.[New], coalesce(cte.[Intermediate], 0) + coalesce(cte.[Old], 0) + coalesce(cte.[New], 0) Total, avg(Value) [avg]from ctecross apply( select cast(Intermediate] as decimal(10, 2)) union all select cast([New] as decimal(10, 2)) union all select cast([Old] as decimal(10, 2))) c(Value) group by Procedure, [Intermediate], [New], [Old]
I got this code at another site but wanted to see what the you SQL guys think I need to do here?Appreciate the helpG