SQL Server - group by 中的用例语句
我试图创建一个视图,如下所示:
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 的不同字段,并且我不知道在聚合字段上工作时如何证明这一点?
我有什么想法可以实现这一点 - 最好是在一个声明中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新了...感谢@Andriy M
Updated... thanks to @Andriy M
您只需要在每个“案例”中包含
group by
即可。像下面这样:
you just need to include the
group by
in each "case".something like the below: