我想在cost
,amt
列中添加值 - 如果在同一日期有同一个人flag
的{{1}} 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
答案 0 :(得分:2)
只是为了多样性,请查看我的解决方案。它使用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启发。
答案 1 :(得分:1)
不确定你想用旗帜做什么,但你需要GROUP BY
喜欢:
SELECT id, date, SUM(cost), Sum(amt), 1 as flag
FROM yourTable
GROUP BY id,date
答案 2 :(得分:0)
SELECT ID, DATE , SUM(COST), SUM(AMT), MIN(Flag)
FROM TABLE
GROUP BY ID, DATE
答案 3 :(得分:0)
如果您需要在同一日期对同一个ID进行标记1和2,那么这应该有效:
SELECT id, date, SUM(cost), SUM(amt) , flag
FROM yourtable a
WHERE flag=1
AND EXISTS (SELECT 1 FROM yourtable b WHERE a.id=b.id AND b.flag=2 AND a.date=b.date)
GROUP BY id, date, flag