Retrive row only if the column 'date' with the latest value have an another column not NULL

a 夏天 提交于 2020-01-06 06:58:08

问题


Let's say I have this table

id  | value | date       | result
----+-------+------------+--------
1   | 1     | 2017-01-01 | NULL 
2   | 1     | 2017-01-02 | NULL 
3   | 2     | 2017-01-03 | NULL 
4   | 1     | 2017-01-04 | NULL  
5   | 2     | 2017-01-05 | NULL 
6   | 3     | 2017-01-06 | NULL 
7   | 1     | 2017-01-07 | NULL 

My goal is to retrieve every "value" for which the last "date" has a "result" equal to NULL.

For instance, with the previous table, my result should look like this:

id  | value | date       | result
----+-------+------------+--------
5   | 2     | 2017-01-05 | NULL
6   | 3     | 2017-01-06 | NULL
7   | 1     | 2017-01-07 | NULL 

The query I use is:

SELECT DISTINCT ON (value) * 
FROM table 
WHERE result IS NULL 
ORDER BY value ASC, date DESC

But when I got this table:

id  | value | date       | result
----+-------+------------+--------
1   | 1     | 2017-01-01 | NULL
2   | 1     | 2017-01-02 | NULL
3   | 2     | 2017-01-03 | NULL
4   | 1     | 2017-01-04 | NULL
5   | 2     | 2017-01-05 | something
6   | 3     | 2017-01-06 | NULL
7   | 1     | 2017-01-07 | NULL

I obtain

id  | value | date       | result
----+-------+------------+--------
4   | 2     | 2017-01-04 | NULL
6   | 3     | 2017-01-06 | NULL
7   | 1     | 2017-01-07 | NULL

instead of

id  | value | date       | result
----+-------+------------+--------
6   | 3     | 2017-01-06 | NULL
7   | 1     | 2017-01-07 | NULL

I tried to use group by / having, but it was more a disaster than else. Is this impossible to do or I'm missing something really simple?


回答1:


You should use the condition outside the query:

select *
from (
    select distinct on (value) * 
    from my_table 
    order by value asc, date desc
    ) s
where result is null
order by id

 id | value |    date    | result 
----+-------+------------+--------
  6 |     3 | 2017-01-06 | 
  7 |     1 | 2017-01-07 | 
(2 rows)


来源:https://stackoverflow.com/questions/50972936/retrive-row-only-if-the-column-date-with-the-latest-value-have-an-another-colu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!