【发布时间】:2019-05-02 10:11:40
【问题描述】:
我有这个GROUP BY 查询,我需要从TABLE_1 中选择一些记录并聚合它们。
SELECTs 相似,但我需要分别聚合 LON 和 BHAM,因为它们是两个不同的概念,但位于同一个表中。
我的问题是我可以在 oracle 中以不同的方式编写以下代码来优化查询的性能吗?
SELECT *
FROM (
( SELECT /*+ full(t1) */
t3.custId AS ID,
t2.secID AS SEC_ID,
t1.org_date AS SETT_DATE,
SUM(t1.amount) AS TOTAL
FROM test.TABLE_1 t1
INNER JOIN test.TABLE_2 t2 on t2.a_code = t1.a_code and t2.c_code = t1.c_code and t2.expiry_date > trunc(sysdate)
INNER JOIN test.TABLE_3 t3 on t3.account_id = t1.account_id
WHERE t1.city = 'LON'
AND t1.amount < 50000 and t1.amount > -50000
GROUP BY t3.custId, t2.secID, t1.org_date
)
UNION ALL
( SELECT /*+ full(t1) */
t3.custId AS ID,
t2.secID AS SEC_ID,
t1.org_date AS SETT_DATE,
SUM(t1.amount) AS TOTAL
FROM test.TABLE_1 t1
INNER JOIN test.TABLE_2 t2 on t2.a_code = t1.a_code and t2.c_code = t1.c_code and t2.expiry_date > trunc(sysdate)
INNER JOIN test.TABLE_3 t3 on t3.account_id = t1.account_id
WHERE t1.city = 'BHAM'
AND t3.alias = 'ABC'
AND t1.amount < 50000 and t1.amount > -50000
GROUP BY t3.custId, t2.secID, t1.org_date
)
)
ORDER BY ID, SEC_ID,
CASE WHEN SETT_DATE < TRUNC(sysdate) THEN trunc(sysdate) ELSE TRUNC(SETT_DATE) end
【问题讨论】:
-
您需要将它们放在单独的行中,还是可以接受单独的列?
-
@Boneist 不接受单独的列,因为我的进程正在使用查询返回并映射到目标的列 ID、SEC_ID、SETT_DATE。我需要将它们放在单独的行中,因为我正在处理每一行
-
好的。顺便说一句,您的查询将失败,因为所选列列表中的
t1.org_date as sett_date与 group by 中的case when t1.org_date < ....不匹配。你的问题是不是打错字了? -
还有,你怎么知道哪一行属于哪个城市?
-
@Boneist 正确,案例最初在选择时出现,我错过了输入 SO。为了暂时保持查询简短,我在 select + group by 中保持它们的一致性
标签: sql oracle query-optimization