SQL 服务器 SUM(添加)产品配件价格

SQL Server SUM (add) prices of accessories to products

我需要汇总主要产品的配件价格。配件和对应产品之间没有link,但是两个产品之间的所有配件都属于前一个产品(见旁注)。

SQL 服务器 2017

输入:

| No | Order | Type      | ProdNo | Price |     side note
--------------------------------------
|  1 | 20213 | Product   | 1320   | 200   |     + 0 + 20
|  2 | 20213 | Accessory | 823    | 0     |     acc. of 1320
|  3 | 20213 | Accessory | 836    | 20    |     acc. of 1320
|  4 | 20213 | Product   | 2680   | 300   |     + 0 + 0 + 0 + 0
|  5 | 20213 | Accessory | 231    | 0     |     acc. of 2680
|  6 | 20213 | Accessory | 536    | 0     |     acc. of 2680
|  7 | 20213 | Accessory | 23     | 0     |     acc. of 2680
|  8 | 20213 | Accessory | 361    | 0     |     acc. of 2680
|  9 | 20213 | Product   | 3320   | 50    |     + 10 + 15
| 10 | 20213 | Accessory | 328    | 10    |     acc. of 3320 
| 11 | 20213 | Accessory | 369    | 15    |     acc. of 3320

输出:

| No | Order | Type      | ProdNo | Price |  
--------------------------------------
|  1 | 20213 | Product   | 1320   | 220   |
|  4 | 20213 | Product   | 2680   | 300   |
|  9 | 20213 | Product   | 3320   | 75    |

我将其理解为一种缺口和孤岛问题。您可以使用 window 函数来解决它:

select *
from (
    select no, order, type, prodNo, sum(price) over(partition by grp) price
    from (
        select
            t.*, 
            sum(case when type = 'Product' then 1 else 0 end) 
                over(partition by orderNo order by no) grp
        from mytable t
    ) t
) t
where type = 'Product'

最内部的查询使用 window 总和来定义记录组。每次遇到产品记录时,都会启动一个新组。中间查询对每个组中的价格求和。最后,最外层查询只过滤产品记录。

通过对每行前的产品数量求和来分配组。然后汇总:

select order, 'Product' as type, 
       max(case when type = 'Product' then prodno end) as prodno,
       sum(price)
from (select t.*,
             sum(case when type = 'Product' then 1 else 0 end) over (partition by order order by no) as grp
      from t
     ) t
group by grp, order