显示今天的当前排名和昨天的排名

时间:2012-10-15 23:52:11

标签: mysql

我有一张包含ID,rank,chart_date和综合浏览量的表格。它基于每晚运行的cron作业,并编译该ID的综合浏览量。

例如:

ID   |   RANK   |   PAGEVIEWS   |  CHART_DATE
5          1           100         2012-10-14
9          2           75          2012-10-14
13         3           25          2012-10-14
9          1           123         2012-10-13
5          2           74          2012-10-13
19         3           13          2012-10-13

所以我抓住今天的图表,基于2012-10-14并将数据按1-3排名。但我也想显示ID在前一天的排名。

例如,2012-10-14 ID 5排名第1,但在2012-10-13排名第2位。

我可以使用一个查询执行此操作吗?或者我必须根据今天循环结果并对每个ID进行查询?

2 个答案:

答案 0 :(得分:2)

  

我可以使用一个查询执行此操作吗?

你可以,但你需要在今天的日期和昨天日期的表格之间加入:

SELECT today.*, yesterday.rank
    FROM yourtable AS today
    JOIN yourtable AS yesterday
        ON (today.id = yesterday.id
            AND today.chart_date = date(now())
            AND yesterday.chart_date = date(date_sub(now(), interval 1 day))
        )
    ORDER BY today.rank DESC;

你甚至可以显示出差异:

SELECT today.*, yesterday.rank AS yest, yesterday.rank-today.rank AS incr
    FROM yourtable AS today
    LEFT JOIN yourtable AS yesterday
        ON (today.id = yesterday.id
            AND today.chart_date = date(now())
            AND yesterday.chart_date = date(date_sub(now(), interval 1 day))
        )
    ORDER BY today.rank DESC;

ID   |   RANK   |   PAGEVIEWS   |  CHART_DATE  |  YEST  |  INCR
5          1           100         2012-10-14     2     |   1
9          2           75          2012-10-14     1     |  -1
13         3           25          2012-10-14     4     |   1

LEFT JOIN确保今天的数据即使昨天也不存在。

答案 1 :(得分:0)

未经测试,但这样的事情应该有效:

select today.id, today.rank, yesterday.rank 
from mytable as today
left join mytable as yesterday on today.id = yesterday.id 
where today.chart_date = 2012-10-14
order by pageviews desc limit 3