如何在详细信息项之间分配标题级折扣

时间:2017-02-13 07:06:42

标签: sql sql-server oracle sql-server-2008 oracle10g

我有2个表格,标题和详细信息。如下所示,头表将有1条记录,详细信息表将有多条记录。现在标题级别有折扣。我想根据每个细节项目的重量分配折扣,并获得实际费率。

enter image description here

感谢。

1 个答案:

答案 0 :(得分:0)

您需要根据(rate * qty)分配折扣作为交易总额的百分比:

WITH transaction_totals AS (

    SELECT   h.header_id
            ,h.discount
            ,SUM(d.rate * d.ty) AS total
    FROM header h
        INNER JOIN detail d
            ON h.header_id = d.header_id
    GROUP BY h.header_id
            ,h.discount

)

SELECT   d.item
        ,d.rate
        ,d.qty
        ,d.total
        --,d.total / tt.total AS DetailPctTotal
        ,tt.discount * (d.total / tt.total) AS DetailDiscount
FROM detail d
    INNER JOIN transaction_totals tt
        ON d.header_id = tt.header_id
;