2015-07-11 64 views
0

我有一個表,看起來像這樣:「變量」,在SQL Server的累積值

id count price 
1 100  2 
2 50  3 
3 10  4 

我想要得到某些累計計數值的價格,例如: 當我「需要」的計數爲120,SQL累積前x行,並檢查第x行中的累積值是否滿足要求(> 120),然後將第x行的價格值返回給我。

120我想拿到3的價格,爲159.5然後4,80 2等

這有可能在SQL Server?

+1

「當我查詢120」是什麼意思? –

+0

您希望價格與您的「變量」最接近的價值(或價值總和)相對應嗎? (這甚至很難問一個關於...的問題) –

+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小提琴例如,80 http://www.sqlfiddle.com/#!6/a1976/6/0

小提琴例如,http://www.sqlfiddle.com/#!6/a1976/7/0

+0

謝謝,它的工作原理!我認爲你的查詢比下面的查詢更快? (我想在短時間內查詢它幾千次) –

+1

Np,由於分析函數只有一次訪問表(因爲沒有連接回同一個表),所以它應該快一點 –

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 

fiddle