I am trying to create a view as follows:
CREATE VIEW vw1 AS SELECT
Town
, case when (Spend > 0 and NbOrders > 0)
then sum(Spend)/sum(NbOrders)
else null
end as AvgSpend
, case when (Margin > 0 and NbOrders > 0)
then sum(Margin)/sum(NbOrders)
else null
end as AvgMargin
FROM Table
group by Town
But I get an error because the fields used in my ‘case when…’ statement aren’t included in an aggregate function.
I can’t use a ‘where’ clause because the average fields depend on different fields being >0 and I can’t see how I could make the case when work on an aggregated field?
Any ideas how I can achieve this – preferably in a single statement?
Updated… thanks to @Andriy M