从 sql 服务器中的各个行获取最大 ID 行
get max ID row from individual rows in sql server
我有如下数据,多行数据相同,可以通过 ID 识别。
我需要如下数据。仅获取每组重复记录的单个最大 ID 值,可以通过获取单个最大 ID
来完成
你能帮我解决这个问题吗?
您可以使用子查询进行过滤。假设您的 table 的列名为 id
、date
和 col
,那将是:
select t.*
from mytable t
where t.col = (select max(t1.col) from mytable t1 where t1.id = t.id)
为了提高性能,请考虑 (id, col)
上的索引。
一个有效的方法——具有正确的索引——是一个相关的子查询:
select t.*
from t
where t.individual = (select max(t2.individual) from t t2 where t2.id = t.id);
正确的索引在 (id, individual)
。
这应该对你有帮助
create table #sample (type char(1), date datetime, Id bigint)
insert into #sample values('A', '5/22/2019 4:33', 1065621)
insert into #sample values('A', '5/22/2019 4:33', 1065181)
insert into #sample values('A', '5/22/2019 4:33', 1064212)
insert into #sample values('B', '11/7/2017 1:07', 540180)
insert into #sample values('B', '11/7/2017 1:07', 540179)
insert into #sample values('B', '11/7/2017 1:07', 540177)
select * from #sample
select [type], [date], max(id)
from #sample
group by [type], [date]
select distinct [type], [date], max(id) over(partition by [type], [date] )
from #sample
Drop table #sample
我有如下数据,多行数据相同,可以通过 ID 识别。
我需要如下数据。仅获取每组重复记录的单个最大 ID 值,可以通过获取单个最大 ID
来完成你能帮我解决这个问题吗?
您可以使用子查询进行过滤。假设您的 table 的列名为 id
、date
和 col
,那将是:
select t.*
from mytable t
where t.col = (select max(t1.col) from mytable t1 where t1.id = t.id)
为了提高性能,请考虑 (id, col)
上的索引。
一个有效的方法——具有正确的索引——是一个相关的子查询:
select t.*
from t
where t.individual = (select max(t2.individual) from t t2 where t2.id = t.id);
正确的索引在 (id, individual)
。
这应该对你有帮助
create table #sample (type char(1), date datetime, Id bigint)
insert into #sample values('A', '5/22/2019 4:33', 1065621)
insert into #sample values('A', '5/22/2019 4:33', 1065181)
insert into #sample values('A', '5/22/2019 4:33', 1064212)
insert into #sample values('B', '11/7/2017 1:07', 540180)
insert into #sample values('B', '11/7/2017 1:07', 540179)
insert into #sample values('B', '11/7/2017 1:07', 540177)
select * from #sample
select [type], [date], max(id)
from #sample
group by [type], [date]
select distinct [type], [date], max(id) over(partition by [type], [date] )
from #sample
Drop table #sample