DB2 子查询最佳实践
Posted
技术标签:
【中文标题】DB2 子查询最佳实践【英文标题】:DB2 Subquery Best Practice 【发布时间】:2021-09-02 16:21:09 【问题描述】:我需要编写一个执行 9 个子查询以从另一个表中获取状态日期的 DB2 查询。由于所有子查询,查询运行非常缓慢。我想知道是否有更优化的方法来做到这一点。有什么建议么? SQL如下:
SELECT BILL_NUMBER,
(SELECT MIN(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'ASSGN' and char(ORDER_ID) = BILL_NUMBER) as "FIRST ASSGN",
(SELECT MAX(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'ASSGN' and char(ORDER_ID) = BILL_NUMBER) as "LAST ASSGN",
(SELECT MAX(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'D-CPICKED' and char(ORDER_ID) = BILL_NUMBER) as "LAST DC PICKED",
(SELECT MIN(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'CONTACTED' and char(ORDER_ID) = BILL_NUMBER) as "FIRST CONTACTED STATUS",
(SELECT MIN(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'UNLOADED' and char(ORDER_ID) = BILL_NUMBER) as "FIRST UNLOADED STATUS",
(SELECT MIN(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'CHECKIN' and char(ORDER_ID) = BILL_NUMBER) as "FIRST CHECKIN STATUS",
(SELECT MIN(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'LHDISP' and char(ORDER_ID) = BILL_NUMBER) as "FIRST LHDISP STATUS",
(SELECT MAX(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'LHDISP' and char(ORDER_ID) = BILL_NUMBER) as "LAST LHDISP STATUS",
(SELECT MAX(Changed) FROM TMWIN.ODRSTAT WHERE STATUS_CODE = 'D-DISP' and char(ORDER_ID) = BILL_NUMBER) as "LAST DDISP STATUS"
FROM TMWIN.TLORDER
WHERE pick_up_by >= '8/1/2021' and pick_up_by <= '8/3/2021'
【问题讨论】:
【参考方案1】:使用条件聚合:
SELECT BILL_NUMBER,
MIN(CASE WHEN OS.STATUS_CODE = 'ASSGN' THEN OS.Changed END) as first_assign,
MAX(CASE WHEN OS.STATUS_CODE = 'ASSGN' THEN OS.Changed END) as last_assign,
. .
FROM TMWIN.TLORDER O JOIN
TMWIN.ODRSTAT OS
ON CHAR(OS.ORDER_ID) = O.BILL_NUMBER
WHERE pick_up_by >= DATE '2021-08-01' AND
pick_up_by <= DATE '2021-08-03'
GROUP BY O.BILL_NUMBER;
【讨论】:
以上是关于DB2 子查询最佳实践的主要内容,如果未能解决你的问题,请参考以下文章