我必须将一个带有2个参数的表联接起来,以显示明细的最新更新状态,以检查MAX /(...)/ MIN(...)的完成/进行中。我该怎么办?
我尝试了LEFT JOIN,但它返回了空值
SELECT a.showonly
, a.want_this_parameter_lastdate
, min(a.xdate) start
, max(a.xdate) stop
, b.lastdate
FROM samedatabase a
LEFT JOIN (SELECT xdate lastdate
, want_this_parameter_lastdate
FROM samedatabase
WHERE ROWNUM = 1
ORDER BY xdate DESC) b
ON a.want_this_parameter_lastdate = b.want_this_parameter_lastdate
WHERE something IN (SELECT DISTINCT equalsomething
FROM another WHERE input like '...')
AND xdate> sysdate - 7
GROUP BY a.showonly, a.want_this_parameter_lastdate, b.lastdate
ORDER BY start ASC;
查询后我得到了
showonly|want_this_parameter|start |stop |lastdate
a1 |b1* |5/7/19 |6/7/19 |(null)
a2 |b2** |6/7/19 |7/7/19 |(null)
a3 |b1* |7/7/19 |8/7/19 |(null)
a4 |b2** |9/7/19 |10/7/19|(null)
a5 |b4 |10/7/19|11/7/19|(null)
我希望这个( stop 是a1中使用的最后一个b1, lastdate 是a1中使用的最后一个b1所有表格)
showonly|want_this_parameter|start |stop |lastdate
a1 |b1* |5/7/19 |6/7/19 |12/17/19--Last B1 used
a2 |b2** |6/7/19 |7/7/19 |11/17/19--Last B2 used
a3 |b1* |7/7/19 |8/7/19 |12/17/19--Last B1 used
a4 |b2** |9/7/19 |10/7/19|12/17/19--Last B2 used
a5 |b4 |10/7/19|11/7/19|12/17/19--Last B4 used
*Same b1
**Same b2
更新 我终于明白了,但仍然担心查询时间 因为MAX(...)将获取整个表,对不对? 我该如何改善此性能。
SELECT a.showonly
, a.want_this_parameter_lastdate
, min(a.xdate) start
, max(a.xdate) stop
, b.lastdate
FROM samedatabase a
LEFT JOIN (SELECT MAX(xdate) lastdate, want_this_parameter_lastdate
FROM samedatabase
GROUP BY want_this_parameter_lastdate) b
ON a.want_this_parameter_lastdate = b.want_this_parameter_lastdate
WHERE something IN (SELECT DISTINCT equalsomething
FROM another
WHERE input like '...')
AND xdate> sysdate - 7
GROUP BY a.showonly, a.want_this_parameter_lastdate, b.lastdate
ORDER BY start ASC;
答案 0 :(得分:2)
我认为简单的子查询可以使工作更快,从而消除不必要的双重分组:
select showonly, parameter, min(xdate) min_dt, max(xdate) max_dt,
(select max(xdate) from samedatabase where parameter = s1.parameter) lst_dt
from samedatabase s1
where xdate > sysdate - 7
and something in (select equalsomething from another where input like 'i%')
group by showonly, parameter