简体   繁体   English

SQL`GROUP BY`和`MAX()`

[英]SQL `GROUP BY` and `MAX()`

Language    Date
----------------------
HTML        2017-03-15
HTML        2017-03-15
HTML        2017-03-19
JavaScript  2017-03-12
JavaScript  2017-03-17
PHP         2017-03-15
PHP         2017-03-17
PHP         2017-03-18
PHP         2017-03-18

I need a result grouped by language with the second column a COUNT() of each language row from the latest date entry. 我需要一个按language分组的结果,第二列是最新日期条目中每种语言行的COUNT() Not all languages have entries on the same dates. 并非所有语言在同一日期都有条目。

For the table above, results should be: 对于上表,结果应为:

HTML        1
JavaScript  1
PHP         2

Here is one method: 这是一种方法:

select language, count(*)
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.language = t.language
               )
group by language;

This uses a correlated subquery go match the most recent date for each language. 这将使用相关的子查询去匹配每种语言的最新日期。 There are other methods, such as using a join or: 还有其他方法,例如使用join或:

select language, count(*)
from t
where (t.language, t.date) in (select t2.language, max(t2.date)
                               from t t2
                               group by t2.language
                             )
group by language;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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