我被困在这里将近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)
答案 0 :(得分:1)
移除Sum
并将查询设为Sub-select
并在outer Query
中执行求和。
此外,当Case
为A.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