I need to preserve one row per group of names from table:
ID | Name | Attribute1| Attribute2 | Attribute3
1 | john | true | 2012-20-10 | 12345670
2 | john | false | 2015-20-10 | 12345671
3 | james | false | 2010-02-01 | 12345672
4 | james | false | 2010-02-03 | 12345673
5 | james | false | 2010-02-06 | 12345674
6 | sara | true | 2011-02-02 | 12345675
7 | sara | true | 2011-02-02 | 12345676
...according to specified criteria. In first place should be preserved rows with true in Attribute1 (if present), then with max date (Attribute2), and if that's not result in one row - the one with max Attribute3.
Desired result is:
ID|Name|Attribute1|Attribute2|Attribute3
1 | john | true | 2012-20-10 | 12345670
5 | james | false | 2010-02-06 | 12345674
7 | sara | true | 2011-02-02 | 12345676
I tried to do that with nested joins, but that seems to be overly complicated. Some simply solution is to first do the SQL result of ORDER BY:
CREATE TABLE output AS
SELECT
ID,
Name,
Attribute1,
Attribute2,
Attribute3
FROM input
ORDER BY
Name,
Attribute1 DESC,
Attribute2 DESC,
Attribute3 DESC;
and do the loop for each row and check and cache if name occurred before - if not, preserve it (and cache name in some global variable), else delete row.
Is there any other pure SQL solution?
For Postgresql:
select distinct on (name) *
from t
order by name, attribute1 desc, attribute2 desc, attribute3 desc
https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT