我有一个简单的查询,我想知道它是否可以更优雅地编码。最终解决方案必须符合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
所以我希望输出为
value 9
它基于上述查询。
我对这个解决方案并不满意 - 有没有更好的方法来实现这个目标?
答案 0 :(得分:5)
您可以使用:
SELECT TOP 1
x.value
FROM @t x
ORDER BY x.due_date DESC, x.version DESC
但是,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
但这需要一个支持该功能的数据库--MySQL没有,PostgreSQL只在v8.4中启动...
答案 1 :(得分:1)
SELECT
value
FROM
@t T1
LEFT OUTER JOIN @t T2 ON
T2.id = T1.id AND
(
(T2.due_date > T1.due_date) OR
(T2.due_date = T1.due_date AND T2.version > T1.version)
)
WHERE
T2.id IS NULL
...或
SELECT
value
FROM
@t T1
WHERE
NOT EXISTS
(
SELECT
FROM
@t T2
WHERE
T2.id = T1.id AND
(
(T2.due_date > T1.due_date) OR
(T2.due_date = T1.due_date AND T2.version > T1.version)
)
)