如何有效地从SQL Server上的最后一行批量获取值
我有一张这样的桌子如何有效地从SQL Server上的最后一行批量获取值,sql,sql-server,aggregate-functions,Sql,Sql Server,Aggregate Functions,我有一张这样的桌子 Id | Type | Value -------------------- 0 | Big | 2 1 | Big | 3 2 | Small | 3 3 | Small | 3 我想要一张这样的桌子 Type | Last Value -------------------- Small | 3 Big | 3 我怎样才能做到这一点。我知道有一个SQL Server方法名为LAST_VALUE(…)OVER.(…),但我无法将其用于分组方式 我
Id | Type | Value
--------------------
0 | Big | 2
1 | Big | 3
2 | Small | 3
3 | Small | 3
我想要一张这样的桌子
Type | Last Value
--------------------
Small | 3
Big | 3
我怎样才能做到这一点。我知道有一个SQL Server方法名为LAST_VALUE(…)OVER.(…),但我无法将其用于分组方式
我也尝试过使用selectmax(ID)
&selecttop1..
,但这似乎有点低效,因为每个值都有一个子查询。当表中有几百万行时,查询花费的时间太长
有没有一种方法可以快速获取这些值的最后一个值,可以使用last\u value
?您可以使用rownumber:
select
type,
value
from
(
select
type,
value,
rownumber() over (partition by type order by id desc) as RN
) TMP
where RN = 1
由于SQL Fiddle似乎不起作用,所以现在无法测试此问题,但希望这没问题。您可以使用rownumber进行测试:
select
type,
value
from
(
select
type,
value,
rownumber() over (partition by type order by id desc) as RN
) TMP
where RN = 1
由于SQL Fiddle似乎不起作用,所以现在无法测试此问题,但希望这没问题。您可以使用rownumber进行测试:
select
type,
value
from
(
select
type,
value,
rownumber() over (partition by type order by id desc) as RN
) TMP
where RN = 1
由于SQL Fiddle似乎不起作用,所以现在无法测试此问题,但希望这没问题。您可以使用rownumber进行测试:
select
type,
value
from
(
select
type,
value,
rownumber() over (partition by type order by id desc) as RN
) TMP
where RN = 1
现在无法测试这一点,因为SQL Fiddle似乎不起作用,但希望这没问题。我真的想知道是否有更有效的解决方案,但是,我使用以下查询来满足这些需求
Select Id, Type, Value
From ( Select *, Max (Id) Over (Partition By Type) As LastId
From #Table) T
Where Id = LastId
我真的很想知道是否有更有效的解决方案,但是,我用下面的问题来询问这些需求
Select Id, Type, Value
From ( Select *, Max (Id) Over (Partition By Type) As LastId
From #Table) T
Where Id = LastId
我真的很想知道是否有更有效的解决方案,但是,我用下面的问题来询问这些需求
Select Id, Type, Value
From ( Select *, Max (Id) Over (Partition By Type) As LastId
From #Table) T
Where Id = LastId
我真的很想知道是否有更有效的解决方案,但是,我用下面的问题来询问这些需求
Select Id, Type, Value
From ( Select *, Max (Id) Over (Partition By Type) As LastId
From #Table) T
Where Id = LastId
最有效的方法可能是notexists
,它对基础运算符使用反联接:
select type, value
from likeso l
where not exists (select 1 from likeso l2 where l2.type = l.type and l2.id > l.id)
为了提高性能,您需要在likeso(type,id)
上建立索引,最有效的方法可能是not exists
,它对基础运算符使用反联接:
select type, value
from likeso l
where not exists (select 1 from likeso l2 where l2.type = l.type and l2.id > l.id)
为了提高性能,您需要在likeso(type,id)
上建立索引,最有效的方法可能是not exists
,它对基础运算符使用反联接:
select type, value
from likeso l
where not exists (select 1 from likeso l2 where l2.type = l.type and l2.id > l.id)
为了提高性能,您需要在likeso(type,id)
上建立索引,最有效的方法可能是not exists
,它对基础运算符使用反联接:
select type, value
from likeso l
where not exists (select 1 from likeso l2 where l2.type = l.type and l2.id > l.id)
对于性能,您需要一个关于likeso(type,id)
的索引这是这个问题的标准问题:这是这个问题的标准问题:这是这个问题的标准问题:这是这个问题的标准问题:这是非常巧妙的!这是难以置信的巧妙!这是难以置信的巧妙!这是难以置信的巧妙!