SQL Server SUM(添加)产品的附件价格

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

我需要汇总主要产品的附件价格。附件和对应产品之间没有链接,但是两个产品之间的所有附件都属于先前的产品(请参阅旁注)。

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-server sum sql-server-2017
2个回答
0
投票

您可以使用sum()功能和inner join尝试以下查询。

SELECT tblA.*
    ,tblB.TotalAmount
FROM (
    SELECT [No]
        ,[Order]
        ,ProdNo
        ,Type
    FROM ProductSales
    ) tblA
INNER JOIN (
    SELECT [Order]
        ,sum(Price) AS TotalAmount
    GROUP BY [Order]
    ) tblB ON tblA.[Order] = tblB.[Order]
    where Type = 'Product'

0
投票

您可以使用窗口功能:

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
© www.soinside.com 2019 - 2024. All rights reserved.