我有这张表,我想计算每个 TYPE_MATERIAL/YEARS 的累积百分比
declare @mytable table (TYPE_MATERIAL int, YEARS int, ROW_NUM int, PERCENTUAL_PRICE numeric(6,2))
insert @mytable
select 1,2010,1,54.5
union all select 1,2010,2,37.5
union all select 1,2010,3,8.0
union all select 1,2009,1,72.8
union all select 1,2009,2,21.0
union all select 1,2009,3,6.2
union all select 2,2010,1,61.0
union all select 2,2010,2,36.0
union all select 2,2010,3,3.0
结果应该是这样的:
TYPE_MATERIAL YEARS ROW_NUM PERCENTUAL_PRICE PERCENTUAL_PRICE_cumulative
1 2010 1 54.50 54.5 (=54.5)
1 2010 2 37.50 92.0 (=54.5+37.5)
1 2010 3 8.00 100.0 (=54.5+37.5+8)
1 2009 1 72.80 72.8
1 2009 2 21.00 93.8
1 2009 3 6.20 100.0
2 2010 1 61.00 61.0
2 2010 2 36.00 97.0
2 2010 3 3.00 100.0
我在 Internet 上找到了这个查询,但它不适用于这种情况,因为它仅在我有一个 TYPE_MATERIAL 和一个 YEARS 时才计算累积百分比
select TYPE_MATERIAL, YEARS, ROW_NUM, PERCENTUAL_PRICE,
PERCENTUAL_PRICE_cumulative=
(
select SUM(PERCENTUAL_PRICE) from @mytable b
where b.ROW_NUM<=a.ROW_NUM
)
from @mytable a
有什么建议么?谢谢