SQL查询在给定时间范围内提取最高值?

时间:2016-08-01 20:43:58

标签: php mysql sql

我在sql查询时遇到问题。我需要花费最近30天,然后仅删除4个结果,其中“投票”值更大

db结构

Id |    time    | voting
1  | unix time  | 3
2  | unix time  | 2
3  | unix time  | 4
4  | unix time  | 1
5  | unix time  | 6

我想带我的数据只有:5-3-1-2

我试过

select a.* 
from table a 
inner join 
    ( select votingng, max(time) as latest from table group by voting) v 
        on a.time = v.latest 
        and a.voting = v.voting 
order by time desc limit

4 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

select v.*
from voting v
where timestamp >= unix_timestamp(date_sub(curdate(), interval 1 month)
order by voting desc
limit 4;

答案 1 :(得分:1)

听起来你正试图在过去30天内获得前4名投票结果。这些中的任何一个都能满足您的需求吗?

SELECT a.*
  FROM table a
 WHERE a.time > UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 30 DAY))
 ORDER BY a.voting DESC
 LIMIT 4;

SELECT a.*
  FROM table a
 WHERE DATEDIFF( NOW(), FROM_UNIXTIME(a.time) ) <= 30 
 ORDER BY a.voting DESC
 LIMIT 4;

答案 2 :(得分:0)

希望这就是你要找的东西:

Select *
From
    Voting
Where
    time Between CURDATE() And DATE_SUB(CURDATE(),INTERVAL 30 DAY)
Order By voting Desc 
Limit 4

答案 3 :(得分:0)

如果您使用的是teradata

,请尝试此操作
SELECT * from table
qualify row_number () over(order by time desc)=1 ;

select * from 
(select table.*, row_number () over(order by time desc) as RANK from table)
where RANK=1