SQL:为每个类别选择最近的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6680568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL: Select most recent date for each category
提问by Wilduck
I'm pulling data from a database and one of the tables contain two columns that together identify a location and another column containing a date of each time it was serviced. Is it possible to write a SQL query such that I get the most recent time that each location was serviced?
我正在从数据库中提取数据,其中一个表包含两列共同标识一个位置,另一列包含每次服务的日期。是否可以编写 SQL 查询,以便获得每个位置服务的最近时间?
So if my raw data looks like this:
因此,如果我的原始数据如下所示:
category_a category_b date
1 a 1/1/01
1 a 2/2/02
1 b 1/2/01
1 b 2/3/02
2 a 1/3/01
2 a 2/4/02
2 b 1/4/01
2 b 2/5/02
then the query would return this:
然后查询将返回:
category_a category_b date
1 a 2/2/02
1 b 2/3/02
2 a 2/4/02
2 b 2/5/02
This would be easy to do if the database was authored in such a way that the category combinations were stored in a separate table. However, I don't control this database, so I can't make changes to it.
如果数据库的创作方式是将类别组合存储在单独的表中,那么这将很容易做到。但是,我不控制此数据库,因此无法对其进行更改。
采纳答案by Tom H
SELECT
category_a,
category_b,
MAX(date)
FROM
Some_Unnamed_Table
GROUP BY
category_a,
category_b
ORDER BY
category_a,
category_b
I certainly don't mind helping people when I can, or I wouldn't be on this site, but did you really search for an answer for this before posting?
我当然不介意在我可以的时候帮助别人,或者我不会在这个网站上,但是你真的在发布之前搜索过这个问题的答案吗?
回答by Bohemian
This is a simple "group by" using the fact the the "most recent" date is the "highest valued", or max()
, date
这是一个简单的“分组依据”,使用“最近”日期是“最高值”或max()
日期这一事实
select category_a, category_b, max(date)
from mytable
group by category_a, category_b
order by category_a, category_b -- The ORDER BY is optional, but the example data suggests it's needed
回答by Muhammad Usama
select category_a, category_b, max( date) from tbl group by category_a ,category_b;
选择 category_a, category_b, max( date) from tbl group by category_a ,category_b;
回答by BugFinder
Try
尝试
select category_a, category_b, max(date) as last_update from table group by category_a, category_b