给出一个表
ID FRUIT
-- -----
1 APPLE
2 BANANA
3 PEAR
4 APPLE
5 APPLE
6 PEAR
我想得到这个
ID FRUIT RUNNING_TOTAL
-- ----- -------------
1 APPLE 1
2 BANANA 1
3 PEAR 1
4 APPLE 2
5 APPLE 3
6 PEAR 2
(按照ID顺序,我们第一次遇到给定的水果时,我们将该行的RUNNIN_TOTAL值设置为1;第二次遇到给定的水果时,RUNNIN_TOTAL为2,依此类推。)< / p>
我想我需要先添加一个这样的列:
alter table Fruits add RUNNING_TOTAL int null
然后用这样的东西设置新列的值
update Fruits set RUNNING_TOTAL = ...
但我不知道如何完成最后的陈述。有人可以帮忙吗?我正在使用SQL SERVER 2008,但便携式解决方案将是理想的。
谢谢!
答案 0 :(得分:3)
select id, fruit, row_number() over (partition by fruit order by id) as running_total
from fruits
order by id
然后,
alter table Fruits add RUNNING_TOTAL int null
update fruits set running_total = subquery.running_total
from fruits
inner join (
select id, row_number() over (partition by fruit order by id) as running_total
from fruits
)subquery on fruits.id = subquery.id
select * from fruits
答案 1 :(得分:2)
在SQL Server 2008中,您可以使用可更新的CTE:
with toupdate as (
select f.*, row_number() over (partition by fruit order by id) as seqnum
from fruits f
)
update toupdate
set running_total = seqnum;
我不会真的称之为#34; running_total&#34;。它似乎更像是一个&#34; sequence_number&#34;对我来说。 &#34; Running_total&#34;建议累积总和。