我有一个看起来像这样的表:
id count price
1 100 2
2 50 3
3 10 4
我想得到某些累积计数值的价格,例如: 当我“需要”120的计数时,SQL累计前x行,并检查第x行中的累积值是否满足要求(> 120)然后给我回去x'的价格值排。
对于120我想得到3作为价格,159.5然后4,80 a 2等。
在SQL Server中可以吗?
答案 0 :(得分:3)
认为你想要这个:
select top 1
[price]
from(
select [id],
[count],
[price],
sum([count]) over(order by [id]) as run_sum
from tbl
) x
where 120 <= run_sum
order by run_sum
小提琴: http://www.sqlfiddle.com/#!6/a1976/5/0
159.5的小提琴示例,http://www.sqlfiddle.com/#!6/a1976/6/0
答案 1 :(得分:1)
select top 1 price from
(
select t1.id, t1.count, SUM(t2.count) as sum, t1.price
from table_name t1
inner join table_name t2 on t1.id >= t2.id
group by t1.id, t1.count, t1.price
) t where t.sum >= 120 order by sum