Mysql 从查找表中获取每个类型和每个日期的最大ID
我想为每个日期的每个类型保留最高的报告id(报告id) 注意:数据列有多个日期,下面仅显示2021年1月1日 问题:t1是我需要使用的查找表,我的挑战是它不包含供参考的日期列Mysql 从查找表中获取每个类型和每个日期的最大ID,mysql,sql,greatest-n-per-group,Mysql,Sql,Greatest N Per Group,我想为每个日期的每个类型保留最高的报告id(报告id) 注意:数据列有多个日期,下面仅显示2021年1月1日 问题:t1是我需要使用的查找表,我的挑战是它不包含供参考的日期列 select t2.* from t2 where t1.Report_ID = (select max(t1.Report_ID) from t1 where t2.Date = ??? and t2.Types = ???
select t2.*
from t2
where t1.Report_ID = (select max(t1.Report_ID)
from t1
where t2.Date = ??? and t2.Types = ???
);
t1
报告ID
名称
价值
1.
名字1
值1
2.
名称2
价值2
3.
名字3
价值3
这回答了问题的原始版本 我想为每个日期的每个类型保留最高的报告id(报告id) 此操作不需要参考表。您的逻辑应该在子查询中使用
t2
执行您想要的操作:
select t2.*
from t2
where t2.Report_ID = (select max(tt2.Report_ID)
from t2 tt2
where tt2.Date = t2.date and tt2.Type = t2.Type
);
您可以使用
不存在
,如下所示:
select t2.*
from t2
--join t1 on t1.Report_ID = t2.Report_ID -- use it if you want data from t1 in SELECT
where not exists
(select 1 from t2 t22
where t22.date = t2.date and t22.type = t2.type
and t22.Report_ID > t2.Report_ID)
使用此查询:
SELECT Date, Types, MAX(Report_ID) Report_ID
FROM t2
GROUP BY Date, Types
对于每个日期和类型
将其连接到t1
:
SELECT t2.Date, t2.Types, t1.Name, t1.Value, t1.Report_ID
FROM t1
INNER JOIN (
SELECT Date, Types, MAX(Report_ID) Report_ID
FROM t2
GROUP BY Date, Types
) t2 ON t2.Report_ID = t1.Report_ID
请参阅。
结果:
日期
类型
名称
价值
报告ID
2020-01-01
类型1
名称2
价值2
2.
2020-01-01
类型3
名字3
价值3
3.
使用:
您可以通过row_number()和CTE轻松实现这一点。首先,我们需要将t1和t2连接起来,以从t1中获得值列。对于给定日期的特定类型,我们使用row_number()在每一行中放置一个序列号,从最高报告ID到最低报告ID。
然后,我们只考虑具有最低序列号的行,它代表给定DA的任何特定类型的最高RePurtId。
With cte as
(
select t2.date,t2.types,t2.report_id,t2.name ,t1.value ,row_number () over (partition by date,types order by t2.report_id desc) RowNumber
from t2 inner join t1 on t2.report_id=t1.report_id
)
select date_format(date,"%Y.%m.%d") date,types,name,value,report_id from cte where RowNumber=1
输出:
用您正在使用的数据库标记您的问题。它清楚地显示SQL。请。您可以通过检查来检查如何创建可回答的SQL问题。@astentx已更正。谢谢。@您不需要t1中的日期列作为参考,因为两个表中都有报表id。对不起,我错误地在t1中键入了。事实上它没有。对不起,我错加了t1。事实上它没有。
With cte as
(
select t2.date,t2.types,t2.report_id,t2.name ,t1.value ,row_number () over (partition by date,types order by t2.report_id desc) RowNumber
from t2 inner join t1 on t2.report_id=t1.report_id
)
select date_format(date,"%Y.%m.%d") date,types,name,value,report_id from cte where RowNumber=1