问:数据库一张表中有不同公司不同时间发来的数据,怎样取每个公司最新的那条数据呢?
答:使用分析函数row_number() over (partiion by ... order by ...)来进行分组编号,然后取分组标号值为1的记录即可。目前主流的数据库都有支持分析函数。
其中,partition by 是指定按哪些字段进行分组,这些字段值相同的记录将在一起编号;order by则是指定在同一组中进行编号时是按照怎样的顺序。
以sql server为例:
select
s.*
from
(
select
*, row_number() over (partition
by
[公司名]
order
by
[时间] desc)
as
group_idx
from
[表名]
) s
where
s.group_idx = 1
ps:如果只需要找出每组中不同的数据,用distinct就可以实现。
例:
select distinct [列名] from [表名]