Mysql group by 选择最近的记录

标签 mysql greatest-n-per-group

我有一个包含组织 ID 的报告表,例如,每年都有多行。

| ID | Organisation ID | Report Year 
--------------------------------------
|  1 |   1             | 2016        
|  2 |   1             | 2017        
|  3 |   12            | 2016        
|  4 |   12            | 2017        
|  5 |   13            | 2016        
|  6 |   13            | 2017        
|  7 |   14            | 2016        

和一个report_files表如下

| ID | Report Type ID | Report ID   | Report File
---------------------------------------------------
|  1 | 1              | 1          | org1_test_report_2016.pdf
|  3 | 1              | 3          | org1_test_report_2016.pdf
|  5 | 1              | 5          | org1_test_report_2016.pdf
|  6 | 1              | 6          | org1_test_report_2017.pdf
|  7 | 1              | 7          | org1_test_report_2016.pdf

我想从报告表中获取最新记录,即如果存在 2016 年和 2017 年行,我想获取 2017 年,如果仅存在 2016 年,则获取该记录并将其左连接到 reports_file 表上以获取 report_file 列如果该 id 存在,则使用文件名,如果不存在则返回 null。像这样的东西。

| Report ID | Organisation ID | Report File
----------------------------------------------
| 2         | 1               | NULL
| 4         | 12              | NULL
| 6         | 13              | org1_test_report_2017.pdf
| 7         | 14              | org1_test_report_2016.pdf

可能没有正确解释,如果问题不清楚,请告诉我。基本上想要按报告表上的organization_id进行分组,但获取最新的行,如果2017年存在则获取该行,如果不存在则获取2016年,然后在report_files表上将其左连接以查看文件是否附加到最新的报告ID(如果有)返回文件,否则返回 null。希望这是有道理的。

提前致谢。

最佳答案

试试这个:

SELECT C.Report_ID, A.Organisation_ID, C.Report_File 
FROM
(SELECT Organisation_ID, MAX(Report_Year) Latest_Report_Year
FROM reports GROUP BY Organisation_ID) A 
JOIN reports B ON A.Organisation_ID=B.Organisation_ID AND A.Latest_Report_Year=B.Report_Year
JOIN report_files C ON B.ID=C.Report_ID;

查看它在 SQL Fiddle 上运行.

关于Mysql group by 选择最近的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49735158/

相关文章:

php - 如果已选中,如何将复选框值插入数据库表?

mysql - 在 Node 循环中选择和插入未按预期工作

mySQL:这是递归(或相互依赖)的一种形式吗?

SQL - 返回编号最高的标题

mysql - SQL 为 MySQL 上的帐户选择最后一条记录

php - 如何在数据库中每行创建一个有效的删除/更新按钮

mysql - CakePHP:在非 HABTM 关系上使用联接表

mysql - MySQL 中的查询和子查询向客户显示购买的产品

sql - sql中如何查找列中的最小值

sql - Postgres根据时间戳选择不同的