选择组中的第一行

时间:2013-12-30 22:50:20

标签: sql sqlite

我正在使用此查询在一小时内获得第一个数据:

select * 
from
(   
    select time_stamp, value 
    from tbl 
    order by time_stamp desc
) 
group by strftime('%m%d%H',time_stamp) 
order by time_stamp;

它给了我正确的结果,但是由于有大量数据点和有限的硬件资源而导致速度很慢。 如果不在GROUP之前进行排序,它会快得多,但随后我会从随机的小时部分得到值。 有什么建议吗?

示例返回值:

select ts, t1 from temperatura group by strftime('%m%d%H',ts) order by ts limit 5;
2013-12-22 09:59:01|22062
2013-12-22 10:59:02|21937
2013-12-22 11:59:02|21937
2013-12-22 12:57:02|22000
2013-12-22 13:59:02|21625

select * from(select ts, t1 from temperatura order by ts desc) group by strftime('%m%d%H',ts) order by ts limit 5;
2013-12-22 09:58:48|22000
2013-12-22 10:00:02|22000
2013-12-22 11:00:02|21937
2013-12-22 12:00:02|21937
2013-12-22 13:19:41|21812

如你所见,我得到了不同的答案。第二个是我想要的。

2 个答案:

答案 0 :(得分:1)

除非我在问题中遗漏了某些内容

SELECT top 10 time_stamp, value 
FROM 
(
    select time_stamp, value
    from tbl 
    order by time_stamp desc
)
group by strftime('%m%d%H',time_stamp)
order by time_stamp; 

SqLite中的等价物:

How to get Top 5 records in SqLite?

也许没有必要两次订购

答案 1 :(得分:0)

在SqLite中,而不是前10名,使用限制10

SELECT ts, t1 
FROM 
(
    select ts, t1
    from temperatura 
    order by ts desc
)
group by strftime('%m%d%H',ts)
order by ts
Limit 10;