SQL Server – instruction de cas d'utilisation dans le groupe par

J'essaie de créer une vue comme suit:

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 

Mais j'obtiens une erreur car les champs utilisés dans mon instruction 'cas quand …' ne sont pas inclus dans une fonction d'agrégat.

Je ne peux pas utiliser une clause 'where' car les champs moyens dépendent de différents champs étant> 0 et je ne vois pas comment je pourrais faire le cas lorsque je travaille sur un champ agrégé?

Des idées comment je peux y parvenir – de preference dans une seule déclaration?

Mise à jour … merci à @Andriy M

 SELECT town ,SUM(CASE WHEN Spend > 0 and NbOrders > 0 THEN Spend END) /SUM(CASE WHEN Spend > 0 and NbOrders > 0 THEN NbOrders END) As AvgSpend ,SUM(CASE WHEN Margin > 0 and NbOrders > 0 THEN Margin END) / SUM(CASE WHEN Margin > 0 and NbOrders > 0 THEN NbOrders END) As AvgMargin FROM table GROUP BY town 
 CREATE VIEW vw1 AS SELECT Town , SUM(CASE WHEN Spend > 0 THEN Spend END) / SUM(CASE WHEN NbOrders > 0 THEN NbOrders END) AS AvgSpend , SUM(CASE WHEN Margin > 0 THEN Margin END) / SUM(CASE WHEN NbOrders > 0 THEN NbOrders END) AS AvgMargin FROM Table GROUP BY Town 

il suffit d'inclure le group by dans chaque "cas".

quelque chose comme le ci-dessous:

 CREATE VIEW vw1 AS SELECT Town , case when (Spend > 0 and NbOrders > 0) then sum(Spend)/sum(NbOrders) group by Town else null end as AvgSpend , case when (Margin > 0 and NbOrders > 0) then sum(Spend)/sum(NbOrders) group by Town else null end as AvgMargin FROM Table 
 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(Spend)/sum(NbOrders) else null end as AvgMargin FROM Table group by Town, AvgSpend, AvgMargin