Search code examples
mysqljoincountsumwindow-functions

Get column sum and use it for distribute a value


I have 2 tables, sales_order and sales_order_line.

sales_order table contains a detail of a transaction in transaction level and sales_order_line table contains a detail in SKU (item) level. I joined those 2 tables and realized that discount value is on transaction level. When customer bought more than 1 item, I need to distribute the value of discount based on item price and when customer bought just 1 item, discount value just applied as it is. The tables look like this.

sales_order

ID   | PLATFORM_ORDER_CODE | OMS_ORDER_CODE | DISCOUNT_TOTAL
0001          19000001         nebula0001         300000
0002          19000001         nebula0002         300000
0003          19000001         nebula0003         300000
0004          19000002         nebula0004         100000
0005          19000002         nebula0005         100000
0006          19000003         nebula0006          50000

sales_order_line

SALES_ORDER_ID | PLATFORM_ORDER_CODE | SKU_CODE | UNIT_PRICE
0001                   19000001        SKUA0001     200000
0002                   19000001        SKUA0002     100000
0003                   19000001        SKUA0003     300000
0004                   19000002        SKUA0001     200000
0005                   19000002        SKUA0002     100000
0006                   19000003        SKUA0001     200000

This is my attempt on DB Fiddle and I need the result to be like this

PLATFORM_ORDER_CODE | OMS_ORDER_CODE | SKU_CODE | UNIT_PRICE | DISCOUNT
19000001                 nebula0001    SKUA0001     200000      100000
19000001                 nebula0002    SKUA0002     100000      50000
19000001                 nebula0003    SKUA0003     300000      150000
19000002                 nebula0004    SKUA0001     200000      66666.6666
19000002                 nebula0005    SKUA0002     100000      33333.3333
19000003                 nebula0006    SKUA0001     200000      50000

Solution

  • SELECT B.PLATFORM_ORDER_CODE, 
           A.OMS_ORDER_CODE, 
           B.SKU_CODE, 
           B.UNIT_PRICE, 
           A.DISCOUNT_TOTAL/C.TOTAL_PRICE*B.UNIT_PRICE DISCOUNT
    FROM t_td_sales_order A
    JOIN t_td_sales_order_line B ON B.SALES_ORDER_ID = A.ID
    JOIN ( SELECT PLATFORM_ORDER_CODE, SUM(UNIT_PRICE) TOTAL_PRICE
           FROM t_td_sales_order_line
           GROUP BY PLATFORM_ORDER_CODE ) C ON B.PLATFORM_ORDER_CODE = C.PLATFORM_ORDER_CODE
    

    fiddle