gpt4 book ai didi

Mysql group by 选择最近的记录

转载 作者:行者123 更新时间:2023-11-29 06:45:21 25 4
gpt4 key购买 nike

我有一个包含组织 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com