鉴于表格定义:
create table mytable (
id integer,
mydate datetime,
myvalue integer )
我希望通过单个SQL查询获得以下答案:
id date_actual value_actual date_previous value_previous
其中:
date_previous is the maximum of all the dates preceeding date_actual
for each id and values correspond with the two dates
{max(date_previous) < date_actual ?}
我怎样才能做到这一点?
感谢您的提示
答案 0 :(得分:1)
这是每周在StackOverflow上出现的常见“每组最大N”查询的变体。
SELECT m1.id, m1.mydate AS date_actual, m1.myvalue AS value_actual,
m2.mydate AS date_previous, m2.myvalue AS value_previous
FROM mytable m1
LEFT OUTER JOIN mytable m2
ON (m1.id = m2.id AND m1.mydate > m2.mydate)
LEFT OUTER JOIN mytable m3
ON (m1.id = m3.id AND m1.mydate > m3.mydate AND m3.mydate > m2.mydate)
WHERE m3.id IS NULL;
换句话说,m2
是具有相同id
和较小mydate
的所有行,但我们只想要一个没有行m3
的行m1
和m2
之间的日期。假设日期是唯一的,m2
中只有一行,这是真的。
答案 1 :(得分:0)
假设我正确理解了你的要求,你可以试试这里。
select a.id,
a.mydate as date_actual,
a.value as value_actual,
b.date as date_previous,
b.value as value_previous
from mytable a, mytable b
where a.id = b.id and
a.mydate > b.mydate and
b.mydate = (select max(mydate) from mytable c where c.id = a.id and c.mydate < a.mydate)
为丑陋的SQL道歉。我相信有更好的方法可以做到这一点。