根据字符串检索组中的最后一条记录 - DB2

Retrieve last record in a group based on string - DB2

我在 DB2 数据库中有一个 table 交易数据,我想检索每个位置和产品的最后一条记录。不幸的是,日期存储为 YYYYMMDD 字符串。没有我可以输入的交易 ID 或类似字段。没有主键。

DATE LOCATION PRODUCT QTY
20210105 A P1 4
20210106 A P1 3
20210112 A P1 7
20210104 B P1 3
20210105 B P1 1
20210103 A P2 6
20210105 A P2 5

我想检索显示每个位置、每个产品的最后一笔交易的结果,因此结果应该是:

DATE LOCATION PRODUCT QTY
20210112 A P1 7
20210105 B P1 1
20210105 A P2 5

我查看了类似问题的答案,但出于某种原因无法从解决类似问题的答案跳到适用于我的环境的代码。

编辑:我试过下面的代码,摘自对 this question 的回答。它 returns 单个 location/part 组合的多行。我已经尝试过该问题中的其他答案,但没有运气让他们执行。

SELECT * 
FROM t 
WHERE DATE > '20210401' AND DATE in (SELECT max(DATE) 
FROM t GROUP BY LOCATION) order by PRODUCT desc

谢谢!

您可以使用 lead() 获取更改前的最后一行:

select t.*
from (select t.*,
             lead(date) over (partition by location, product order by date) as next_lp_date,
             lead(date) over (order by date) as next_date
      from t
     ) t
where next_lp_date is null or next_lp_date <> next_date

您可以使用 ROW_NUMBER()。例如,如果你的 table 被称为 t 你可以这样做:

select * 
from (
  select *,
    row_number() over(partition by location, product 
                      order by date desc) as rn
  from t
) x
where rn = 1

看起来您只需要在子选择中匹配您的键。

SELECT * 
FROM t T1
WHERE DATE > '20210401' 
AND DATE in (SELECT max(DATE) FROM t T2 WHERE T2.Location = T1.Location and T2.Product=T1.Product)