Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select multiple columns but group by only 1 column

I have a comment table

comment_id when_added
10 02/23/2022
21 02/23/2022
10 02/24/2022

I needed to get the count, comment_id, and the latest when_added

comment_id when_added count
10 02/24/2022 2
21 02/23/2022 1

I tried this query

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT COUNT(*) as count, comment_id, when_added 
FROM comment GROUP BY  comment_id, when_added ORDER BY  when_added DESC;

Is there a way to group by only using comment_id?

>Solution :

You should group only by comment_id and get the last when_added for each comment_id with MAX() aggregate function:

SELECT comment_id, 
       MAX(when_added) last_when_added, 
       COUNT(*) count
FROM comment 
GROUP BY comment_id 
ORDER BY last_when_added DESC;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading