简体   繁体   中英

SQL, Finding Counts of a Group By MAX

Basically, I have a MySQL table with comments, which have IDs and dates submitted, and I want users to be able to edit these comments. When a comment is edited, I'd like to create a new entry in the table with the same ID as the comment being edited, but a new date.

So when I'm selecting my list of comments, I want to use SELECT MAX( DateSubmitted ) ... Group By ID , but I'd also like to get a count of the number of IDs that are grouped for each one, so I know how many times a comment has been edited.

I think it should be something like this:

SELECT ID, COUNT(1) as "Number of edits"
FROM comments
GROUP BY ID;

Merged with:

SELECT ID, MAX(`DateSubmitted`), Comment
FROM comments
GROUP BY ID;

If you want to get the latest comment text as well as the date edited and count:

SELECT a.ID, a. MaxDateSubmitted, a.NumComments, b.Comment
(SELECT ID, 
        MAX(`DateSubmitted`) as "MaxDateSubmitted", 
        COUNT('ID') as "NumComments"
FROM comments
GROUP BY ID) a
INNER JOIN comments b ON a.ID = b.ID and b.DateSubmitted = a.MaxDateSubmitted;

Note : this assumes no two edits have exactly the same date and time (down to the precision of the time portion). But in this case, I think this is a valid assumption.

If you just want the latest edit date and count:

 SELECT ID, 
        MAX(`DateSubmitted`) as "MaxDateSubmitted", 
        COUNT('ID') as "NumComments"
 FROM comments
 GROUP BY ID
SELECT ID, COUNT(ID) as "Number of edits", MAX(`DateSubmitted`)
FROM comments
GROUP BY ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM