Mysql查询为给定的项目编号获取最近2个

时间:2008-12-09 23:58:28

标签: sql mysql

我的数据库中有以下属性。

  

统计ID,设备名称,值,时间戳。

对于给定的统计信息,我想找到每个唯一设备的2个最新时间戳和相应的值。

我正在尝试像

这样的东西

试验1)

select statistic, devicename, value, timestamp
from X_STATSVALUE
where statistic=19
order by orgtime DESC limit 2;

这为我提供了前2个时间戳,但不是每个设备。

试验2)

select statistic, devicename, value, timestamp
from X_STATSVALUE as x 
where x.statistic=241
  and (select count(*)
       from X_STATSVALUE as y
       where y.statistic=x.statistic
         and y.device=x.device
         and y.timestamp > x.timestamp) <=1;

但这也不太好..

基本上,对于给定的统计信息,我希望最新的2个时间戳记包含每个设备的值..任何帮助都非常感谢:)

3 个答案:

答案 0 :(得分:2)

这就是我解决这类问题的方法:

SELECT x.statistic, x.devicename, x.value, x.timestamp
FROM X_STATSVALUE AS x
  LEFT OUTER JOIN X_STATSVALUE AS x2
    ON (x.statistic = x2.statistic 
    AND x.devicename = x2.devicename 
    AND x.timestamp < x2.timestamp)
GROUP BY x.statistic, x.devicename
HAVING COUNT(*) < 2;

换句话说,显示行,使得少于两个具有相同statisticdevicename以及更大(更近期)timestamp的行。

我假设您在timestamp列中没有给定统计数据和副本的重复项设备名。

答案 1 :(得分:1)

尝试类似:

SELECT DISTINCT x.statistic, x.devicename, x.value, x.timestamp
FROM X_STATSVALUE AS x
WHERE x.timestamp IN (SELECT timestamp
                      FROM X_STATSVALUE
                      WHERE devicename = x.devicename AND statistic = x.statistic
                      ORDER BY timestamp LIMIT 2)

(虽然可能不适用于旧的MySQL)

答案 2 :(得分:1)

我在我的系统上测试了以下查询,并且像你的那样有一个演示表,它可以工作。我考虑过orgtime而不是时间戳...你可以做同样的事情(只需更改姓名)

    select t1.statistic, devicename, value, timestamp from X_STATSVALUE as t1 

    inner join 

    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) 
as t2 

    on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime

    UNION

    select tb1.statistic, tb1.devicename, tb1.value, tb1.timestamp
    from X_STATSVALUE as tb1 inner join 

    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE  WHERE statistic+orgtime not in 
    (select t1.statistic+t1.orgtime from X_STATSVALUE as t1 inner join 
    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) 
as t2 on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime
    ) group by statistic 
    ) 

    as tb2 on tb1.statistic = tb2.statistic and tb1.orgtime = tb2.orgtime
豫ICP备18024241号-1