【问题标题】:SQL Server SUM (add) prices of accessories to productsSQL Server SUM(添加)产品配件的价格
【发布时间】:2020-03-25 09:57:42
【问题描述】:

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

SQL Server 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    |

【问题讨论】:

  • “配件和对应产品之间没有链接” -- 这需要更改架构并创建此类链接。

标签: sql sql-server tsql window-functions gaps-and-islands


【解决方案1】:

我将其理解为一种差距和孤岛问题。您可以使用如下窗口函数来解决它:

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'

最内部的查询使用窗口总和来定义记录组。每次满足产品记录时,都会启动一个新组。中间查询将每个组中的价格相加。最后,最外层的查询只过滤产品记录。

【讨论】:

    【解决方案2】:

    通过汇总每行之前的产品数量来分配组。然后聚合:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多