1

我有一个包含 ID、排名、chart_date 和页面浏览量的表格。它基于每晚运行并编译该 ID 的综合浏览量的 cron 作业。

例如:

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 排名第一,但在 2012 年 10 月 13 日,它排名第二。

我可以用一个查询来做到这一点吗?或者我是否必须遍历基于今天的结果并查询每个 ID?

4

2 回答 2

2

我可以用一个查询来做到这一点吗?

可以,但是您需要在具有今天日期的表和具有昨天日期的表之间进行 JOIN:

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确保今天的数据存在,即使昨天的数据不存在)。

于 2012-10-16T00:04:06.780 回答
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
于 2012-10-16T00:04:14.937 回答