如何找到不同行中两个日期之间的差异,以获得唯一的记录组合

时间:2017-05-29 10:55:31

标签: sql oracle

为了比较不同列的日期,我使用了以下查询,问题是我需要为prod_status,pckg,lbl的所有组合找到相同的内容 下面我只是用于单一组合

SELECT p_id,trunc(eff_dt),TRUNC(end_dt),
LEAD(trunc(eff_dt),1) OVER (ORDER BY eff_dt)AS prev_eff_dt,
LEAD(TRUNC(end_dt),1) OVER (ORDER BY end_dt)AS prev_end_dt,
COALESCE(LEAD(eff_dt,1) OVER (ORDER BY eff_dt)-TRUNC(end_dt),NULL)
FROM pm
WHERE p_id IN (61) AND prod_status='8001' AND pckg='20' AND lbl='00075'
ORDER BY p_id

1 个答案:

答案 0 :(得分:0)

您可以根据子查询在where子句中使用表达式列表,该子查询将返回id 61的所有组合。

这是查询:

SELECT p_id,trunc(eff_dt),TRUNC(end_dt),
LEAD(trunc(eff_dt),1) OVER (ORDER BY eff_dt)AS prev_eff_dt,
LEAD(TRUNC(end_dt),1) OVER (ORDER BY end_dt)AS prev_end_dt,
COALESCE(LEAD(eff_dt,1) OVER (ORDER BY eff_dt)-TRUNC(end_dt),NULL)
FROM pm
WHERE (prod_status, pckg, lbl) IN (select prod_status, pckg, lbl
                                     from pm
                                   where p_id = '61')
ORDER BY p_id;

或没有提供ID:

SELECT p_id,trunc(eff_dt),TRUNC(end_dt),
LEAD(trunc(eff_dt),1) OVER (ORDER BY eff_dt)AS prev_eff_dt,
LEAD(TRUNC(end_dt),1) OVER (ORDER BY end_dt)AS prev_end_dt,
COALESCE(LEAD(eff_dt,1) OVER (ORDER BY eff_dt)-TRUNC(end_dt),NULL)
FROM pm
WHERE (prod_status, pckg, lbl) IN (select prod_status, pckg, lbl
                                     from pm)
ORDER BY p_id;

如果有帮助,请告诉我。