问题
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