这是我的数据
ID VER_ID DUE_DATE
1478 1.0 28-MAR-16
1352 1.0 8-MAY-17
1479 2.0 28-MAR-17
1481 2.0 9-June-17
当我按due_date desc和group by ver_id排序时,我需要识别所有不按降序排列的行ID。
用我的上述数据 预期结果:(因为版本2.0的ID与日期 - 降序对齐)
ID VER_ID DUE_DATE
1478 1.0 28-MAR-16
1352 1.0 8-MAY-17
答案 0 :(得分:2)
嗯。 “不按降序排列”的一个定义是该值大于前一个值或小于下一个值。
有了这个定义:
select t.*
from (select t.*,
lag(due_date) over (order by id) as prev_due_date,
lead(due_date) over (order by id) as next_due_date,
from t
) t
where prev_due_date < due_date or next_due_date > due_date;
答案 1 :(得分:2)
您可以使用&#34; LAG&#34;分析功能。 它会给你&#34; ID&#34;前一行的列值,您可以将其与&#34; ID&#34;进行比较。当前行的列。
例如 - 在下面的emp表中,记录由&#34; hiredate&#34; desc和case语句正在检查&#34; empno&#34;这比之前的员工&#34; empno&#34;少。因此,对于第一列&#34; FLAG&#34;在表格中,如果EMPNO没有下降,则给出&#34; 0&#34;别的&#34; 1&#34;。
SELECT (CASE
WHEN empno > lag (empno) OVER (ORDER BY hiredate desc) THEN 0
ELSE 1
END) as flag, a.*
FROM emp a
ORDER BY hiredate DESC;
表:EMP
FLAG | EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO
--------+---------------+---------------+---------------+---------------+-------------------+---------------+-----------+---------
1 | 7876 | ADAMS | CLERK | 7788 | 12-Jan-83 | 1100 | | 20
1 | 7788 | SCOTT | ANALYST | 7566 | 9-Dec-82 | 3000 | | 20
0 | 7934 | MILLER | CLERK | 7782 | 23-Jan-82 | 1300 | | 10
1 | 7902 | FORD | ANALYST | 7566 | 3-Dec-81 | 3000 | | 20
1 | 7900 | JAMES | CLERK | 7698 | 3-Dec-81 | 950 | | 30
1 | 7839 | KING | PRESIDENT | | 17-Nov-81 | 5000 | | 10
1 | 7654 | MARTIN | SALESMAN | 7698 | 28-Sep-81 | 1250 | 1400 | 30
0 | 7844 | TURNER | SALESMAN | 7698 | 8-Sep-81 | 1500 | 0 | 30
1 | 7782 | CLARK | MANAGER | 7839 | 9-Jun-81 | 2450 | | 10
1 | 7698 | BLAKE | MANAGER | 7839 | 1-May-81 | 2850 | | 30
1 | 7566 | JONES | MANAGER | 7839 | 2-Apr-81 | 2975 | | 20
1 | 7521 | WARD | SALESMAN | 7698 | 22-Feb-81 | 1250 | 500 | 30
1 | 7499 | ALLEN | SALESMAN | 7698 | 20-Feb-81 | 1600 | 300 | 30
1 | 7369 | SMITH | CLERK | 7902 | 17-Dec-80 | 800 | | 20