SQL Server:多行的 SUM() 包括 where 子句
我有一个如下所示的表格:
PropertyID Amount Type EndDate
--------------------------------------------
1 100 RENT null
1 50 WATER null
1 60 ELEC null
1 10 OTHER null
2 70 RENT null
2 10 WATER null
将有多个项目向一个属性计费,并且也多次计费。例如,租金可以向房产 #1 计费 12 次(一年多),但是我唯一感兴趣的是那些 ENDDATE 为 null(换句话说,当前)的房产,
我想实现:
PropertyId Amount
--------------------------
1 220
2 80
我已经尝试过像这样的事情:
SELECT
propertyId,
SUM() as TOTAL_COSTS
FROM
MyTable
但是,在 SUM 中,我是否会被迫进行多次选择,以返回每种类型费用的当前金额?我可以看到这变得混乱,我希望有一个更简单的解决方案
有什么想法吗?
I have a table that looks something like the following :
PropertyID Amount Type EndDate
--------------------------------------------
1 100 RENT null
1 50 WATER null
1 60 ELEC null
1 10 OTHER null
2 70 RENT null
2 10 WATER null
There will be multiple items billed to a property, also billed multiple times. For example RENT could be billed to property #1 12 times (over a year), however the only ones I'm interested for are those with ENDDATE of null (in otherwords, current)
I would like to achieve :
PropertyId Amount
--------------------------
1 220
2 80
I have tried to do something like this :
SELECT
propertyId,
SUM() as TOTAL_COSTS
FROM
MyTable
However, in the SUM would I be forced to have multiple selects bringing back the current amount for each type of charge? I could see this becoming messy and I'm hoping for a much simpler solution
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这将返回每个属性和类型的总计
这将仅返回活动值
,这将返回属性的总计
......
This will bring back totals per property and type
This will bring back only active values
and this will bring back totals for properties
......
试试这个:
Try this:
您的意思是为 EndDate 为 null 的每个属性获取 sum(所有类型的金额):
you mean getiing sum(Amount of all types) for each property where EndDate is null:
听起来你想要类似的东西:
sounds like you want something like:
从概念上讲,
WHERE
子句始终在GROUP BY
之前应用(显然,执行计划可以执行其想要的操作)。它必须位于查询中的GROUP BY
之前,并在SUM之前充当过滤器
SUM
,这就是大多数答案的方式在这里工作。您还应该注意可选的
HAVING
子句,该子句必须位于GROUP BY
之后。这可用于在GROUP
ing之后过滤组的结果属性 - 例如HAVING SUM(Amount) > > 0
The
WHERE
clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to theGROUP BY
. It must come before theGROUP BY
in the query, and acts as a filter before things areSUM
med, which is how most of the answers here work.You should also be aware of the optional
HAVING
clause which must come after theGROUP BY
. This can be used to filter on the resulting properties of groups afterGROUP
ing - for instanceHAVING SUM(Amount) > 0
使用通用表表达式添加总计行,
order by
需要top 100
才能正常工作。Use a common table expression to add grand total row,
top 100
is required fororder by
to work.