I have 4 tables with this detail on each table
deli_order Table
order_code | code | plat_create_time | status OC001 C001 2019-04-14 Success OC002 C002 2019-04-14 Success OC003 C003 2019-04-14 Success
pg_order Table
id |order_code | code | plat_create_time 1 OC001 C001 2019-04-14 2 OC002 C002 2019-04-14 3 OC003 C003 2019-04-14
pg_package Table
pg_order_id | plat_create_time | cm_sign_time 1 2019-04-14 2019-04-14 2 2019-04-14 2019-04-14 3 2019-04-14 -
pg_send_package Table
order_code | code | plat_create_time | lp_sign_time OC001 C001 2019-04-14 - OC002 C002 2019-04-14 - OC003 C003 2019-04-14 2019-04-14
I need to count transaction data that have either ‘cm_sign_time’ or ‘lp_sign_time’. The pg_package table need to be joined first to pg_order, after that it can be joined to deli_order table.
First I try to join the pg_send_package table with deli_order table first. This is my query
SELECT DATE(A.create_time) AS 'Create Time', SUM(CASE WHEN B.lp_sign_time IS NOT NULL THEN 1 ELSE 0 END) AS 'Completed Order' FROM deli_order A INNER JOIN pg_send_package B ON B.order_code = A.order_code AND B.code = A.code WHERE DATE(A.plat_create_time) = '2019-04-14' GROUP BY DATE(A.plat_create_time);
and the result
Create Time | Completed Order 2019-04-14 130
But when I join the other 2 table, the result i got is nothing. This is my query
SELECT DATE(A.plat_create_time) AS 'Create Time', SUM(CASE WHEN B.lp_sign_time IS NOT NULL THEN 1 WHEN D.cm_sign_time IS NOT NULL THEN 1 ELSE 0 END) AS 'Completed Order' FROM deli_order A INNER JOIN pg_send_package B ON B.order_code = A.order_code AND B.code = A.code INNER JOIN pg_order C ON C.order_code = A.order_code AND C.oms_code = A.code INNER JOIN pg_package D ON D.pg_order_id = C.id WHERE DATE(A.plat_create_time) = '2019-04-14' GROUP BY DATE(A.plat_create_time);
This is the result
Create Time | Completed Order
I need to sum the count result from transaction that have either ‘lp_sign_time’ or ‘cm_sign_time’ on it.
My expected result is
Create Time | Completed Order 2019-04-14 150
150 is came from 130 transactions with ‘lp_sign_time’ and 20 transactions with ‘cm_sign_time’ What should i change in my query?
Advertisement
Answer
You can try to use UNION ALL
combine pg_send_package
and pg_package
table make a result set for order_code,code,lp_sign_time
then do OUTER JOIN
with COUNT
.
SELECT DATE(A.plat_create_time) AS 'Create Time', COUNT(lp_sign_time) AS 'Completed Order' FROM deli_order A LEFT JOIN ( SELECT order_code, code, lp_sign_time FROM pg_send_package psp UNION ALL SELECT C.order_code, C.code, pp.cm_sign_time FROM pg_package pp INNER JOIN pg_order C ON pp.pg_order_id = C.id ) t1 ON t1.order_code = A.order_code AND t1.code = A.code AND DATE(A.plat_create_time) = '2019-04-14' GROUP BY DATE(A.plat_create_time);