我目前有一个给定表的前X个结果列表,给定的一天,其中'top'被定义为具有最高聚合计数的结果。我希望能够看到的不仅仅是那个特定日子的数量,还有它与昨天的数量以及上周数量的平均值的比较。
这是我当前的查询:
SELECT foo, bar, SUM(count) as today
FROM tablename
WHERE col1 = 'asdf' and date = '2012-08-23'
GROUP BY foo, bar
ORDER BY count desc
LIMIT 5
结果如下:
|foo | bar | today |
|something1 | something3 | 2345 |
|something2 | something4 | 1234 |
....
但我想拥有的是这样的:
|foo | bar | today | yesterday | week_avg |
|something1 | something3 | 2345 | 2273 | 2193 |
|something2 | something4 | 1234 | 935 | 1001 |
....
作为奖励积分,我不介意在某种GROUP_CONCAT结果中拥有过去20天的所有日期(因此我可以很容易地用它来制作迷你图)
答案 0 :(得分:3)
您可以获取上周的所有行,然后使用条件聚合(通过CASE
expressions)仅将当前日期的count
值和昨天的count
值相加:
SELECT foo,
bar,
SUM(CASE WHEN date = CURDATE() THEN count ELSE 0 END) AS today,
SUM(CASE WHEN date = CURDATE() - INTERVAL 1 DAY THEN count ELSE 0 END) AS yesterday,
AVG(count) AS week_avg
FROM tablename
WHERE col1 = 'asdf' AND
date >= CURDATE() - INTERVAL 1 WEEK
GROUP BY foo,
bar
ORDER BY today DESC
LIMIT 5
最后,我们按今天count
值的总和排序,并根据该订单选择前五名。
答案 1 :(得分:0)
一旦您准备了包含日期和日期金额的汇总表,并假设您正在寻找与昨天的差异,您可以使用COALESCE
。下面的tbl
表引用了您的摘要表,如下所示:
SELECT date, foo, bar, SUM(count) as today
FROM tablename
WHERE col1 = 'asdf'
GROUP BY date, foo, bar
ORDER BY count desc
LIMIT 5
查询
SELECT a.ddate, a.amount AS today,
COALESCE(a.amount -
(SELECT b.amount
FROM tbl b
WHERE b.ddate = a.ddate - INTERVAL 1 DAY), a.amount) AS yesterday
FROM tbl a
请参阅fiddle。
答案 2 :(得分:0)
你的第一个问题。试试这个:
SELECT day0.foo, day0.bar,
day0.addup as today,
day1.addup as yesterday,
week0.addup/7 as week_avg
FROM
(
SELECT foo, bar, SUM(count) as addup
FROM tablename
WHERE col1 = 'asdf'
AND date >= CURDATE()
AND date < CURDATE() + INTERVAL 1 DAY
GROUP BY foo, bar
) day0
JOIN (
SELECT foo, bar, SUM(count) as addup
FROM tablename
WHERE col1 = 'asdf'
AND date >= CURDATE() - INTERVAL 1 DAY
AND date < CURDATE()
GROUP BY foo, bar
) day1 ON (day0.foo = day1.foo AND day0.bar=day1.bar)
JOIN (
SELECT foo, bar, SUM(count) as addup
FROM tablename
WHERE col1 = 'asdf'
AND date >= CURDATE() - INTERVAL 7 DAY
AND date < CURDATE()
GROUP BY foo, bar
) week0 ON (day0.foo = week0.foo AND day0.bar = week0.bar)
ORDER BY day0.addup desc
LIMIT 5
它看起来很毛茸茸,但它是三个不同的摘要查询的连接,每天一个。
你的第二个问题:
SELECT foo, bar, GROUP_CONCAT(addup)
FROM (
SELECT foo, bar,
DATEDIFF(CURDATE(),date) AS daysago,
SUM(count) as addup
FROM tablename
WHERE col1 = 'asdf'
AND date >= CURDATE() - INTERVAL 20 DAY
AND date < CURDATE() )A
GROUP BY foo, bar, date
ORDER BY foo, bar, date