我有一個累積柱產生如下表查詢(累積)累計值減去接管
+--+---+--------+------+
|id|qty|cumulate|value |
+--+---+--------+------+
|1 |5 |5 |419.6 |
+--+---+--------+------+
|2 |2 |7 |167.84|
+--+---+--------+------+
|3 |1 |8 |83.92 |
+--+---+--------+------+
|4 |2 |10 |167.84|
+--+---+--------+------+
|5 |1 |11 |83.92 |
+--+---+--------+------+
|6 |5 |16 |419.6 |
+--+---+--------+------+
不過,我需要進一步的附件查詢只會選擇所有累積到行9.在這種情況下,前4行累計到10位,前3位; 8。
我需要提取其中數量不超過且不小於9的總值的總和。 行按日期順序(日期未顯示),因此行無法重新排序。
如何實現這一目標?
編輯
這裏是我的查詢(但上述結果表是不相同的輸出作爲什麼這個查詢會產生):
select branch,
case
when DATEDIFF(MONTH, dateInv, getDate()) between 0 and 6 then '0-6'
when DATEDIFF(MONTH, dateInv, getDate()) between 7 and 12 then '7-12'
when DATEDIFF(MONTH, dateInv, getDate()) between 13 and 18 then '13-18'
when DATEDIFF(MONTH, dateInv, getDate()) between 19 and 24 then '19-24'
when DATEDIFF(MONTH, dateInv, getDate()) between 25 and 36 then '25-36'
when DATEDIFF(MONTH, dateInv, getDate()) > 36 then '>36'
end [period]
,sum(qty*cost) [costs]
from (
select branch,qty, dateInv, max(cost)cost, max(soh)[qoh], SUM(qty*cost)[sumqty]
, sum(qty) over (partition by product order by dateInv desc) [cumulate]
from openquery(linkedserver,
'select branch,product, soh, cost, dateInv, qty
from table
group by branch,product, soh, cost, dateInv, qty
order by dateInv DESC
')
group by branch,product,qty, dateInv
)t
where cumulate <= qoh
group by branch, dateInv
你想要前三行還是前四行? –
查看查詢將有所幫助 – Carth
因此,使用哪個ID是否重要?假設我們使用ID分別爲6,2和2的ID分別爲5,2和2,共計9個;但它也可以通過使用ID 1,2,3和5來實現,其數量爲5,2,1,1這兩個示例都會生成累計總數爲9的數字,那就是您所追求的內容? – xQbert