SQL-如何获取特定日期之前有记录的最新日期?

时间:2019-04-29 13:32:11

标签: mysql sql date

我有一个如下的表t1:

 -----------------------------
 |    date   |  id   | value |
 -----------------------------
 | 2/28/2019 |  1    | 55  |
 | 2/28/2019 |  2    | 44  |
 | 2/28/2019 |  3    | 33  |
 | 2/26/2019 |  1    | 22  |
 | 2/26/2019 |  2    | 12  |
 | 2/26/2019 |  3    | 11  |
 -----------------------------

我想从t1中获取abc3,然后在同一表t1中查找日期-1天的abc3值,并显示两条记录。

我创建的查询为:

select 
    a.date, a.id, (a.value - b.value) as 'difference-from-previous-day'
FROM 
    t1 a
INNER JOIN
    t1 b
ON 
    a.ID = b.ID
WHERE 
    b.DATE in (dateadd(day, -1, a.DATE));

当所有日期都在那里时,效果很好。

但是日期之间存在间隙(例如,当我们查看星期一的数据并且星期一之前有一个“周末”时)-表t1中没有最后一天-1的数据,因此此查询显示星期一为NULL)...

如何编写查询以提取存在数据的当前日期(而不是-1日期)之前的最后一个日期?

预期结果:

2/28/2019 | 1 | 33     (which is "55 - 22")
2/28/2019 | 2 | 32     (which is "44 - 12")
2/28/2019 | 3 | 22     (which is "33 - 11")

谢谢。

3 个答案:

答案 0 :(得分:0)

您可以使用相关查询:

SELECT t.*, t.value - (
    -- this one selects newest row older than outer row
    SELECT value
    FROM t AS x
    WHERE x.id = t.id
    AND x.date < t.date
    ORDER BY x.date DESC
    LIMIT 1
) AS diff
FROM t
WHERE NOT EXISTS (
    -- this part filters all but the most recent row
    SELECT 1
    FROM t AS x
    WHERE x.id = t.id
    AND x.date > t.date
)

答案 1 :(得分:0)

您似乎想要:

select t1.*
from t1
where t1.value = 'abc'
order by t1.date desc
limit 2;

答案 2 :(得分:0)

您需要像这样在桌子上进行自我联接:

select 
  t.date, 
  t.id,
  t.value - tt.value diff
from t1 t inner join t1 tt
on tt.id = t.id
and tt.date = (select max(date) from t1 where date < t.date)

也许可以将inner join更改为left join来解决每个id没有上一行的情况。
请参见demo
结果:

| date                | id  | diff |
| ------------------- | --- | ---- |
| 2019-02-28 00:00:00 | 1   | 33   |
| 2019-02-28 00:00:00 | 2   | 32   |
| 2019-02-28 00:00:00 | 3   | 22   |