我想在 cost
列中添加值,amt
- 如果同一个人有 flag
1 和 2 id
在同一日期。请帮忙。谢谢你。列是:
id date cost amt flag
455 05/25/2013 150 110 1
455 05/25/2013 20 45 2
456 08/17/2013 140 60 1
456 08/17/2013 15 20 2
457 09/28/2013 135 10 1
457 09/28/2013 8 40 2
458 11/09/2013 10 30 1
输出应该是:
id date cost amt flag
455 05/25/2013 170 155 1
456 08/17/2013 155 80 1
457 09/28/2013 143 50 1
458 11/09/2013 10 30 1
最佳答案
为了多样性,请查看我的解决方案。它使用 over (partition by )
进行计算,使用 distinct
过滤掉重复项。
select distinct o.ID, o.Date,
SUM(o.COST) OVER(PARTITION BY o.ID, o.Date) as cost
,SUM(o.AMT) OVER(PARTITION BY o.ID, o.Date) as amt
,MIN(FLAG) OVER(PARTITION BY o.ID, o.Date) as flag
from orders o
order by o.ID, o.Date
它的灵感来自 this article .
关于sql - 对相同日期和 ID 的列中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24065770/