2017-02-13 98 views
0

我有2個表格,標題和詳細信息。如下所示,表頭將有1條記錄,詳細信息表將包含多條記錄。現在在標題級別上有折扣。我想根據它們的重量分配每個細節項目的折扣並獲得實際費率。如何在詳細信息中分配標題級別折扣

enter image description here

感謝。

回答

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 
; 
+0

感謝。有效。 – user3625561