我有一个查询生成带有累积列(累积)的下表
+--+---+--------+------+
|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。
我需要提取qty不多且不小于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
答案 0 :(得分:0)
从它的外观来看,每1个数量的值为83.92。 9 * 83.92 = 755.28
答案 1 :(得分:0)
感谢大家的尝试。我设法通过使用一系列带有“over(partition by)”,Row_number和计算的嵌套查询来解决这个问题。
很有趣!