从SQL SERVER中获取全局折扣的折扣

时间:2015-01-17 05:06:41

标签: sql-server

我被困在这里将近4个小时。我的invoice_header表中有全局折扣。我想计算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

我得到这样的错误:

  

无法对包含聚合或子查询的表达式执行聚合函数。

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

2 个答案:

答案 0 :(得分:1)

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

此外,当CaseA.global_discount时,您不需要0部分,Discount将为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

答案 1 :(得分:0)

试试这个

;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