我有4张桌子,每张桌子上都有这个细节
deli_order表
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表
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表
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表
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
我需要计算具有“ cm_sign_time”或“ lp_sign_time”的交易数据。 pg_package表需要首先连接到pg_order,然后才能连接到deli_order表。
首先,我尝试首先将pg_send_package表与deli_order表连接在一起。这是我的查询
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);
和结果
Create Time | Completed Order
2019-04-14 130
但是当我加入其他2张桌子时,我得到的结果一无是处。这是我的查询
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);
这是结果
Create Time | Completed Order
我需要对具有'lp_sign_time'或'cm_sign_time'的事务的计数结果求和。
我的预期结果是
Create Time | Completed Order
2019-04-14 150
150来自130个具有'lp_sign_time'的事务和20个具有'cm_sign_time'的事务 我应该在查询中更改什么?
答案 0 :(得分:1)
您可以尝试使用UNION ALL
组合pg_send_package
和pg_package
表为order_code,code,lp_sign_time
生成结果集,然后对OUTER JOIN
进行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);