Select 多列但仅按 1 列分组
Select multiple columns but group by only 1 column
我有评论table
comment_id
when_added
10
02/23/2022
21
02/23/2022
10
02/24/2022
我需要获取计数,comment_id,以及最新的 when_added
comment_id
when_added
count
10
02/24/2022
2
21
02/23/2022
1
我试过这个查询
SELECT COUNT(*) as count, comment_id, when_added
FROM comment
GROUP BY comment_id, when_added
ORDER BY when_added DESC;
有没有办法只用comment_id分组?
您应该仅按 comment_id
分组,并使用 MAX()
聚合函数为每个 comment_id
获取最后一个 when_added
:
SELECT comment_id,
MAX(when_added) last_when_added,
COUNT(*) count
FROM comment
GROUP BY comment_id
ORDER BY last_when_added DESC;
我有评论table
comment_id | when_added |
---|---|
10 | 02/23/2022 |
21 | 02/23/2022 |
10 | 02/24/2022 |
我需要获取计数,comment_id,以及最新的 when_added
comment_id | when_added | count |
---|---|---|
10 | 02/24/2022 | 2 |
21 | 02/23/2022 | 1 |
我试过这个查询
SELECT COUNT(*) as count, comment_id, when_added
FROM comment
GROUP BY comment_id, when_added
ORDER BY when_added DESC;
有没有办法只用comment_id分组?
您应该仅按 comment_id
分组,并使用 MAX()
聚合函数为每个 comment_id
获取最后一个 when_added
:
SELECT comment_id,
MAX(when_added) last_when_added,
COUNT(*) count
FROM comment
GROUP BY comment_id
ORDER BY last_when_added DESC;