SQL取表中某字段的最新日期对应数据

SQL取表中某字段的最新日期对应数据

多条SQL实现,适合数据量比较大的情况

  • SQL为Teradata下代码,其它数据库需作调整
  • 创建临时表,存储要取字段的范围

create multiset volatile table tmp_table
(
	key_name varchar(100),
	last_date varchar(100)
)
ON COMMIT PRESERVE ROWS;

  • 取对应字段及其最新日期

insert into tmp_table
select key_name,max(stat_date) from target_table
group by key_name 

  • 从目标表去对应字段最新日期的数据

select * from target_table a
inner join tmp_table b
on a.key_name = b.key_name and a.stat_date = b.last_date

单条SQL实现,适合数据量比较小的情况

  • 1
 select * from target_table a 
 where stat_date = (
 	select max(stat_date) 
 	from target_table b 
 	where a.key_nam=b.key_nam);
  • 2

select a.* 
from target_table a
where not exists(select 1 
                  from target_table b
                  where b.key_name=a.key_name and b.stat_date>a.stat_date)
                  
  • 3

select a.*
 from target_table a
 inner join
 (select key_name,max(stat_date) as maxstat_date
  from target_table
  group by key_name) b 
  on a.key_name=b.key_name and a.stat_date=b.maxstat_date
  
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值