每组选择最后30个项目

时间:2011-09-24 14:12:18

标签: mysql group-by subquery limit

希望标题有意义。

对于这个例子,我将在我的数据库中有下一个表

measurements
==================================
stn | date        | temp | time  =
1   | 01-12-2001  | 2.0  | 14:30 =
1   | 01-12-2001  | 2.1  | 14:31 =
1   | 03-12-2001  | 1.9  | 21:34 =
2   | 01-12-2001  | 4.5  | 12:48 =
2   | 01-12-2001  | 4.7  | 12:49 =
2   | 03-12-2001  | 4.9  | 11:01 =
==================================

依此类推。

每个站点(stn)有许多测量值,每天一次 。现在我想选择最近30次 测量的每个电台的温度,其中电台至少有30次温度测量。

我正在玩subquerys和group by,但我似乎无法弄明白。

希望有人可以帮助我。

编辑了表格 我的例子过于简单,留下了一条关键信息。请查看问题。

3 个答案:

答案 0 :(得分:2)

select t1.stn,t1.date,t1.temp,t1.rn from (
select *,
   @num := if(@stn = stn, @num + 1, 1) as rn,
   @stn := stn as id_stn
from table,(select @stn := 0, @num := 1) as r
order by stn asc, date desc) as t1
inner join (select `stn`
           from table
          where concat_ws(' ',date,time) >= now() - interval 30 day
          group by `stn`
         having count(*) >= 30) as t
on t1.stn = t.stn
and t1.rn <= 30
order by stn,date desc,time desc

答案 1 :(得分:2)

这是应该选择Last 30 entries where there are at least 30 entries for a station

的查询

此查询基于nick rulez的答案,所以请向他投票

SELECT t1.stn, t1.date, t1.temp, t1.time FROM 
    (
        SELECT *,
            @num := if(@stn = stn, @num + 1, 1) as rn,
            @stn := stn as id_stn
        FROM 
            `tablename`, 
            (SELECT @stn := 0, @num := 1) as r
        ORDER BY stn asc, date desc
    ) as t1
INNER JOIN 
    (
        SELECT `stn`
        FROM `tablename` 
        GROUP BY `stn`
        HAVING COUNT(*) >= 30
    ) as t
ON t1.stn = t.stn
AND t1.rn <= 30
ORDER BY stn, date desc, time desc

我已经在我根据您的架构制作的示例数据库上对其进行了测试,并且工作正常。

要了解有关此类查询的详情,请查看Within-group quotas (Top N per group)

答案 2 :(得分:0)

SELECT stn, date, temp FROM
(
SELECT stn, date, temp, @a:=IF(@lastStn=stn, @a+1, 1) countPerStn, @lastStn:=stn 
FROM cache 
GROUP BY stn, date
ORDER BY stn, date DESC
) as tempTable 
WHERE countPerStn > 30;

我正在寻找的查询,抱歉,如果我的问题“错误”,它会把你推向错误的方向。我会投票给那些帮助我找到所需查询的答案。