SQL Server - group by中的用例语句

时间:2011-08-04 09:02:48

标签: sql sql-server sql-server-2005 view aggregate-functions

我正在尝试按如下方式创建视图:

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

但是我收到一个错误,因为我的'case when ...'语句中使用的字段不包含在聚合函数中。

我不能使用'where'子句,因为平均字段依赖于不同的字段> 0并且我无法看到在聚合字段上工作时如何处理这种情况?

我是如何实现这一目标的 - 最好是在一个声明中?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您只需在每个“案例”中加入group by

如下所示:

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

答案 2 :(得分:0)

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 

答案 3 :(得分:0)

更新...感谢@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