如何确定子表中的行是否具有升序日期?我的样本数据是下一个
表人员
id name
1 Bob
2 Sara
3 Mike
表约会
id id_apt date
1 1 2018-01-31
1 2 2018-01-31
1 3 2018-02-05
2 1 2018-01-15
2 2 2018-01-07
2 3 2018-01-09
3 1 2018-01-18
从我的示例数据中,我应该只得到 2-萨拉行,因为她的约会
2 1 2018-01-15
2 2 2018-01-07
2 3 2018-01-09
不在升序中。如果某人有1个约会或根本没有约会,则该人具有有效的约会,而我只检查有无效约会的人。
预先感谢
答案 0 :(得分:0)
两次调用窗口函数row_number()
表示按ID和按日期排序的顺序是否不同:
select
*,
row_number() over (partition by id order by id_apt) as by_id,
row_number() over (partition by id order by date, id_apt) by_date
from appointments
id | id_apt | date | by_id | by_date
----+--------+------------+-------+---------
1 | 1 | 2018-01-31 | 1 | 1
1 | 2 | 2018-01-31 | 2 | 2
1 | 3 | 2018-02-05 | 3 | 3
2 | 2 | 2018-01-07 | 2 | 1
2 | 3 | 2018-01-09 | 3 | 2
2 | 1 | 2018-01-15 | 1 | 3
3 | 1 | 2018-01-18 | 1 | 1
(7 rows)
在最终查询中,使用布尔聚合bool_or()
:
select a.id, p.name
from (
select
id,
row_number() over (partition by id order by id_apt) as by_id,
row_number() over (partition by id order by date, id_apt) by_date
from appointments
) a
join person p using(id)
group by id, name
having bool_or(by_id <> by_date);
id | name
----+------
2 | Sara
(1 row)