SQL从表中获取每个项目的最新记录

时间:2020-09-03 06:59:38

标签: mysql sql mysql-8.0

我正在尝试查询数据库以使用max(Created_at)并按stockId分组以获取每只股票的最新记录,但是这样做带来了 first id每个项目及其最后 Created_at

我如何才能将最新记录汇总在一起?请帮忙。 我的查询如下:

SELECT a.id as A_id, b.id as B_id, max(b.Created_at) AS Created_at 
  FROM beta b 
 INNER JOIN alpha a ON b.a_id = a.id 
 GROUP BY a.id 

2 个答案:

答案 0 :(得分:3)

您可以使用诸如ROW_NUMBER()之类的分析功能:

SELECT A_id, B_id , Created_at
  FROM
  (
   SELECT a.id as A_id, b.id as B_id , b.Created_at,
          ROW_NUMBER() OVER (PARTITION BY a.id ORDER BY b.Created_at DESC) as rn
     FROM beta b 
     JOIN alpha a ON b.a_id = a.id 
  ) q
  WHERE rn = 1

将您的记录按stockID(a.id)分组,然后按created_at列递减顺序选择最新。如果联系(每个分组的created_at的相等stockId值)很重要,并且所有令人满意的结果都应包括在结果集中,则将ROW_NUMBER()替换为DENSE_RANK()

答案 1 :(得分:0)

据我了解,您需要这样

declare @item table
(
itemid int
,itemname varchar(100)
)
insert into @item
values(1,'A'),(2,'B'),(3,'C')

declare @stock table
(
itemid int
,stockid int
,updatedate datetime
)
insert into @stock
values(1,1,'2020-08-04 13:11'),(1,1,'2020-08-04 14:11')
      ,(1,2,'2020-08-04 15:11'),(1,2,'2020-08-04 14:11') 


select * from @item a
 inner join
(select stockid,itemid,max(updatedate)lastupdatedate from @stock
group by stockid,itemid
)b on a.itemid=b.itemid