【发布时间】:2014-06-03 09:23:06
【问题描述】:
我尝试使用外连接和 max/count/... over partition 将此类 SQL 语句(具有许多子查询)重写为更有效的形式。旧语句:
select a.ID,
(select max(b.valA) from something b where a.ID = b.ID_T and b.status != 0),
(select max(b.valB) from something b where a.ID = b.ID_T and b.status != 0),
(select max(b.valC) from something b where a.ID = b.ID_T and b.status != 0),
(select max(b.valD) from something b where a.ID = b.ID_T)
from tool a;
这里重要的是 - max(b.valD) 有不同的条件。首先我没有注意到这种差异并写了这样的东西:
select distinct a.ID,
max(b.valA) over (partition by b.ID_T),
max(b.valB) over (partition by b.ID_T),
max(b.valC) over (partition by b.ID_T),
max(b.valD) over (partition by b.ID_T),
from tool a,
(select * from something
where status != 0) b
where a.ID = b.ID_T(+);
我可以在 max over partition 的某处使用这种 b.status != 0 的条件吗?或者我应该更好地添加第三个表加入这样的:
select distinct a.ID,
max(b.valA) over (partition by b.ID_T),
max(b.valB) over (partition by b.ID_T),
max(b.valC) over (partition by b.ID_T),
max(c.valD) over (partition by c.ID_T),
from tool a,
(select * from something
where status != 0) b,
something c
where a.ID = b.ID_T(+)
and a.ID = c.ID_T(+);
问题在于选择和连接数百万行,我的示例只是简化了我的查询。谁能帮我实现更高效的sql?
【问题讨论】:
标签: sql oracle window-functions