在 SQL 服务器中获得全球折扣的折扣

Get Discount from Global Discount in SQL SERVER

我被困在这里将近4个小时了。我的 invoice_header table 有全球折扣。我想根据 invoice_detail 中的价值计算 invoice_detail 中每件商品的折扣,最后按 item_code 分组。

问题是我无法对 invoice_detail 中的值求和:

invoice_header : id, global_discount

invoice_detail : id, invoice_header_id, stock_code, value

SELECT SUM(CASE WHEN A.global_discount <> 0  
                THEN ((B.value * A.global_discount /
                    (SELECT SUM(value) FROM invoice_detail WHERE invoice_header_id = A.id)
                    )) 
                ELSE 0 
                END)/1.1
            AS DISCOUNT
        FROM invoice_header A 
            JOIN invoice_detail B
        ON A.id = B.invoice_header_id
        GROUP BY stock_code

我遇到这样的错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

我删减了一些代码。公式为Discount = value * global_discount / sum(value)

删除 Sum 并将查询设为 Sub-select 并在 outer Query 中求和。

你也不需要 Case 部分,当 A.global_discount0Discount 将是 0。试试这个。

SELECT Sum(INT_DISCOUNT) / 1.1 AS Discount,stock_code
FROM   (SELECT stock_code,B.value * A.global_discount / (SELECT Sum(value)
                                              FROM   invoice_detail
                                              WHERE  invoice_header_id = A.id) INT_DISCOUNT
        FROM   invoice_header A
               JOIN invoice_detail B
                 ON A.id = B.invoice_header_id
        ) A 
 Group by stock_code

试试这个

;WITH CTE AS
(        
    SELECT B.*,A.global_discount,SUM(B.value) OVER(PARTITION BY B.invoice_header_id) SUMM
    FROM invoice_header A 
    JOIN invoice_detail B
    ON A.id = B.invoice_header_id
)
SELECT stock_code,SUM(CASE WHEN global_discount = 0 THEN 0 ELSE (VALUE * global_discount)/SUMM END)/1.1 SUMMMM
FROM CTE
GROUP BY stock_code