给定具有缺失记录的数据的最新值

时间:2010-10-01 14:59:27

标签: sql mysql datetime

...其中“缺失记录”与最后记录的值相同,因此没有记录。

可能主观,但我希望有一种标准化的方法。

所以,假设我在MySQL表中有一堆分析。有一些缺失的信息,但如上所述,这是因为它们的先前值与当前值相同。

table "table":

id    value      datetime
1     5          1285891200    // Today
1     4          1285804800    // Yesterday
2     18         1285804800    // Yesterday
2     16         1285771094    // The day before yesterday

正如您所看到的,我今天没有id 2的值。

如果我想从此表中提取“最近的值”(即1的“今天”和2的“昨天”,我该怎么做?我通过运行以下查询来实现它:< / p>

SELECT id, value FROM (SELECT * FROM table ORDER BY datetime DESC) as bleh GROUP BY id

利用子查询首先对数据进行排序,然后依靠“GROUP BY”从每个id中选择第一个值(由于它是有序的,因此是最新的)。但是,我不知道是否推送子查询是获得最新值的最佳方法。

你会怎么做?

理想的表格:

id    value      datetime
1     5          1285891200    // Today
2     18         1285804800    // Yesterday

...谢谢

1 个答案:

答案 0 :(得分:1)

必须爱MySQL才能在子查询中允许订单。 SQL标准不允许这样做:)

您可以使用标准投诉方式重写查询:

select  *
from    YourTable a
where   not exists
        (
        select  *
        from    YourTable b
        where   a.id = b.id
        and     a.datetime < b.datetime
        )

如果在子查询中存在无法拆分的重复项,您可以group by然后选择一个任意值:

select  a.id
,       max(a.value)
,       max(a.datetime)
from    YourTable a
where   not exists
        (
        select  *
        from    YourTable b
        where   a.id = b.id
        and     a.datetime < b.datetime
        )
group by
        a.id

这会选择共享最新a.value的最大datetime。现在datetime对于所有重复行都是相同的,但标准SQL不知道这一点,因此您必须指定一种从相同日期中选择的方法。在这里,我使用的是max,但min甚至avg也可以正常使用。

相关问题