Answer the question
In order to leave comments, you need to log in
Which aggregation function to use in a GROUP BY query?
There is a data sample that I received by SQL query
SELECT ref_id, id, created_at FROM "images"
GROUP BY ref_id, id
ORDER BY created_at desc
LIMIT 20
id ref_id created_at
25553 1 2014-06-07 13:38:46
25408 1 2014-06-07 13:36:42
25105 1 2014-06-07 13:32:43
25068 1 2014-06-07 13:32:16
24986 670 2014-06-07 01:53:49
24978 670 2014-06-07 01:53:44
24977 670 2014-06-07 01:53:43
24862 666 2014-06-07 01:52:15
24050 602 2014-06-07 01:33:43
24051 602 2014-06-07 01:33:43
20963 1818 2014-06-06 03:16:09
19681 1723 2013-06-07 01:37:50
19680 1723 2013-06-07 01:37:49
18452 236 2013-06-07 01:14:36
16913 517 2012-10-05 01:37:09
16750 658 2012-10-05 01:36:34
15229 696 2012-10-05 01:18:52
14416 1192 2012-10-04 21:41:37
14417 1192 2012-10-04 21:41:37
13107 749 2012-03-24 20:08:59
id ref_id created_at
25553 1 2014-06-07 13:38:46
24986 670 2014-06-07 01:53:49
24862 666 2014-06-07 01:52:15
24050 602 2014-06-07 01:33:43
20963 1818 2014-06-06 03:16:09
19681 1723 2013-06-07 01:37:50
18452 236 2013-06-07 01:14:36
16913 517 2012-10-05 01:37:09
16750 658 2012-10-05 01:36:34
15229 696 2012-10-05 01:18:52
14416 1192 2012-10-04 21:41:37
13107 749 2012-03-24 20:08:59
Answer the question
In order to leave comments, you need to log in
I expected to get no more than one row in the sample with each ref_id
select distinct on (ref_id) ref_id, id, created_at from tablename order by ref_id, created_at desc;
I do not know what about group by
But usually it is done by joining itself and choosing the desired (maximum) date.
Or through max() try to pull out the desired date.
Either select * from (subquery where grouping and sorting by max date)
Or just sort by date the query that is.
In general, a lot of options, which one to choose for yourself.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question