SQL SELECT与所选行的累积计算

问题描述 投票:0回答:2

大家好,非常感谢您的帮助。

我被困在查询的计算列上。我想计算每个订单所需单位的项目库存如何减少,因此我在CALCULATEDSTOCK列上有剩余的库存信息。

对于每个文章和颜色和尺寸的第一次出现,CALCULATEDSTOCK是“初始”股票,对于相同的文章和颜色和尺寸的第二次和下一次出现,CALCULATEDSTOCK减少了先前的单位需要,所以我得到了可用的该行的库存。

请注意,STOCK始终与对数据库的直接查询相同。

这是我想得到的结果:

ORDER   ARTICLE  COLOR    SIZE   STOCK   NEEDED   CALCULATEDSTOCK
-----------------------------------------------------------------
43002   1000     GREY     L      13      4        13
43002   1000     GREY     XL     20      5        20
43006   1000     GREY     XL     20      4        15 
43012   1000     GREY     XL     20      6        11
43021   1000     GREY     XL     20      2        5
43021   1000     PURPLE   M      7       2        7
43023   1000     PURPLE   L      6       3        6

在下面找到我尝试但我不能将LAG命令应用于以前的CALCULATEDSTOCK列,因此我无法计算超过两行...

SELECT ORDER, ARTICLE, COLOR, SIZE, STOCK, NEEDED,
CAST( CASE WHEN ARTICLE = LAG(ARTICLE) OVER (ORDER BY ARTICLE, COLOR, SIZE, ORDER)
   AND COLOR = LAG(COLOR) OVER (ORDER BY ARTICLE, COLOR, SIZE, ORDER)
   AND SIZE = LAG(SIZE) OVER (ORDER BY ARTICLE, COLOR, SIZE, ORDER)
THEN 
(lag(STOCK) OVER (ORDER BY ARTICLE, COLOR, SIZE, ORDER))
-(lag(NEEDED) OVER (ORDER BY ARTICLE, COLOR, SIZE, ORDER))

ELSE STOCK
END
AS decimal(8, 2)) AS CALCULATEDSTOCK
.....

在示例中,有三行相同的文章和颜色和尺寸的ORDERS,但可能会有更多...

非常感谢您的耐心和甜蜜的问候!

sql-server calculated-columns lag
2个回答
0
投票

我想你错过了PARTITION。此外,LAG很棒,但如果你只是做一种运行总计,那么使用一些计算的SUM就可以了。首先,您需要在源数据中使用ID;重复的列会弄乱它。

with source (ORDER_id,   ARTICLE,  COLOR ,   SIZE,   STOCK,   NEEDED) as
(
select 43002,   1000   ,  'GREY  ',   'L '  ,   13   ,   4 union all 
select 43002,   1000   ,  'GREY  ',   'XL'  ,   20   ,   5 union all 
select 43006,   1000   ,  'GREY  ',   'XL'  ,   20   ,   4 union all 
select 43012,   1000   ,  'GREY  ',   'XL'  ,   20   ,   6 union all 
select 43021,   1000   ,  'GREY  ',   'XL'  ,   20   ,   2 union all 
select 43021,   1000   ,  'PURPLE',   'M '  ,   7    ,   2 union all 
select 43023,   1000   ,  'PURPLE',   'L '  ,   6    ,   3 
)
select id, order_id, article, color, size, stock, NEEDED, stock + needed - sum(needed) over (partition by ARTICLE, COLOR, SIZE order by id)
from (
    select row_number() over (order by order_id) id, ORDER_id, ARTICLE, COLOR, SIZE, STOCK, NEEDED
    from source
) source_with_id

0
投票

可能有更优雅的方式来做到这一点,但这里有一个选项:

; with CTE as (select *
    , stock - sum(needed) over (partition by ARTICLE, color, size order by ORDER) as CalcNeeded
    , lead(ORDER) over (partition by ARTICLE, color, size order by ORDER) as PrevOrder
from MyTable)

select a.ORDER,
       a.ARTICLE,
       a.color,
       a.size,
       a.stock,
       a.needed,
       ISNULL(b.CalcNeeded, a.stock)
from cte a
left join cte b
on a.ARTICLE= b.ARTICLE and a.color = b.color and a.size = b.size
and a.ORDER = b.PrevOrder
© www.soinside.com 2019 - 2024. All rights reserved.