从查找中获取每种类型和每个日期的最大 ID table

Get max ID for every Type and every Date from a lookup table

我想为每个日期 (Date) 的每个类型 (Types) 保留最高报告 ID (Report_ID)

注意:数据列有多个日期,下面只显示01.01.2021。

问题: t1 是我需要使用的查找 table,我的挑战是它不包含供参考的日期列。

select t2.*
from t2
where t1.Report_ID = (select max(t1.Report_ID)
                     from t1
                     where t2.Date = ??? and t2.Types = ???
                    );

t1

Report_ID Name Value
1 Name 1 Value 1
2 Name 2 Value 2
3 Name 3 Value 3

t2

Date Types Report_ID Name
01.01.2020 Type 1 1 Name 1
01.01.2020 Type 1 2 Name 2
01.01.2020 Type 3 3 Name 3

查看

Date Types Name Value Report_ID
01.01.2020 Type 1 Name 2 Value 2 2
01.01.2020 Type 3 Name 3 Value 3 3

这回答了问题的原始版本。

I want to keep the highest report id (Report_ID) for every type (Types) for every single date (Date)

不需要引用 table。您的逻辑应该在子查询中使用 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
                     );

您可以按如下方式使用NOT EXISTS

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

每个 DateTypes

你得到最大值 Report_ID

加入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

参见demo
结果:

Date Types Name Value Report_ID
2020-01-01 Type 1 Name 2 Value 2 2
2020-01-01 Type 3 Name 3 Value 3 3

使用ROW_NUMBER()

WITH cte AS (
  SELECT t2.*, t1.Value, 
         ROW_NUMBER() OVER(PARTITION BY `Date`, Types ORDER BY Report_ID DESC) AS rn
  FROM t2
  JOIN t1 ON t1.Report_ID = t2.Report_ID
)
SELECT * FROM cte WHERE rn = 1;

db<>fiddle demo

您可以通过 row_number() 和 CTE 轻松实现。首先,我们需要连接 t1 和 t2 以从 t1 中获取 value 列。对于给定日期的特定类型,我们使用 row_number() 在每一行中从最高的 Report_ID 到最低的顺序编号。 然后我们只考虑序列号最低的行,它代表给定 da 的任何特定类型的最高 report_id。

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
  

输出: