Sea*_*ean 5 sql sql-server sql-server-2005 ansi-sql
我有一个简单的查询,我想知道它是否可以更优雅地编码.最终解决方案必须符合ansi标准.
我需要根据日期和版本从表中获取最新值.样本会更清楚地解释:
declare @t table (id int, due_date smalldatetime, version int, value nvarchar(10))
insert into @t select 3, '1/1/2010', 1, 'value 1'
insert into @t select 3, '1/1/2010', 2, 'value 2'
insert into @t select 3, '3/1/2010', 1, 'value 3'
insert into @t select 3, '3/1/2010', 2, 'value 4'
insert into @t select 3, '3/1/2010', 3, 'value 5'
insert into @t select 3, '3/1/2010', 4, 'value 6'
insert into @t select 3, '4/1/2010', 1, 'value 7'
insert into @t select 3, '4/1/2010', 2, 'value 8'
insert into @t select 3, '4/1/2010', 3, 'value 9'
select value from @t t
inner join (select due_date, version=max(version)
from @t where due_date = (select max(due_date) from @t) group by due_date) maxes
on t.due_date=maxes.due_date and t.version=maxes.version
Run Code Online (Sandbox Code Playgroud)
所以我希望输出是
value 9
Run Code Online (Sandbox Code Playgroud)
它基于上面的查询.
我对这个解决方案并不满意 - 有没有更好的方法来实现这个目标?
你可以使用:
SELECT TOP 1
x.value
FROM @t x
ORDER BY x.due_date DESC, x.version DESC
Run Code Online (Sandbox Code Playgroud)
不过,TOP不是ANSI.另一种选择是使用ANSI分析/等级/窗口函数:
SELECT x.value
FROM (SELECT t.value,
ROW_NUMBER() OVER (ORDER BY t.due_date DESC, t.version DESC) AS rank
FROM @t t) x
WHERE x.rank = 1
Run Code Online (Sandbox Code Playgroud)
但这需要一个支持该功能的数据库--MySQL不支持,PostgreSQL仅在v8.4中启动...
| 归档时间: |
|
| 查看次数: |
416 次 |
| 最近记录: |