具有多个日期的MySQL查询

时间:2012-10-02 13:24:53

标签: mysql

我正在尝试根据日期范围(每个帖子的“星星”数量)为应用程序提取一些活动报告

它有一个包含帐户ID的帖子表,以及一个将该ID与帐户绑定的“会员”表。

我知道我能做到:

SELECT
posts.affid,
affiliates.name
sum(posts.stars) AS SEPT_2012
from posts
JOIN affiliates on posts.affid = affiliates.id
WHERE posts.timestamp BETWEEN '2012-09-01' AND '2012-10-01'
group by affid

这将从9月开始提供具有会员ID,姓名和总“星”的结果。一个月

但是,我想做一个可以追溯的数据,获取8月,7月,6月和5月的数字,这些数字会显示在单个查询结果中(因此结果将包括affid,name,SEPT_2012,AUG_2012,JUL_2012 ...等等)。基本上,我假设为其他日期范围做子查询。

有什么建议吗? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

你可能想GROUP BY EXTRACT(YEAR_MONTH FROM timestamp)(除了你想做的其他事情)。当然,它不会为您提供SEPT_2012AUG_2012等列,但数据会在那里。

答案 1 :(得分:0)

虽然您无法动态创建列,但您可以“伪造”它们并为每个日期范围使用UNION。在每个UNION内,您为其他日期列选择0,为正确列选择SUM()

类似的东西应该有效:

SELECT
    posts.affid,
    affiliates.name,
    sum(posts.stars) AS SEPT_2012,
    0 AS AUG_2012,
    0 AS JUL_2012
from
    posts
    JOIN affiliates on posts.affid = affiliates.id
WHERE
    posts.timestamp BETWEEN '2012-09-01' AND '2012-10-01'
group by affid

UNION (
    SELECT
        posts.affid,
        affiliates.name
        0 AS SEPT_2012,
        sum(posts.stars) AS AUG_2012,
        0 AS JUL_2012
    from
        posts
        JOIN affiliates on posts.affid = affiliates.id
    WHERE
        posts.timestamp BETWEEN '2012-08-01' AND '2012-09-01'
    group by affid
)
UNION (
    SELECT
        posts.affid,
        affiliates.name
        0 AS SEPT_2012,
        0 AS AUG_2012,
        sum(posts.stars) AS JUL_2012
    from
        posts
        JOIN affiliates on posts.affid = affiliates.id
    WHERE
        posts.timestamp BETWEEN '2012-07-01' AND '2012-08-01'
    group by affid
)


更新(将单个行中每个affid的所有结果合并)

根据评论,您希望将单行上每个posts.affid的结果与每列中的所有数据合并。您可以通过在上面的完整查询周围放置外部查询然后再次使用GROUP BY affid来实现此目的。有了这个,你应该为每个affid和所有列提供一行代码。我已更新上述查询,为每个空列选择0,而不是null为“更好”输出:

SELECT affid, name, SEPT_2012, AUG_2012, JUL_2012 FROM (
    ... full query above ...
) AS q
GROUP BY affid

更新

要从所有子查询中获取所有“星号”的总和,外部select语句适用于:

  SELECT affid, name, sum(SEPT_2012), sum(AUG_2012), sum(JUL_2012) FROM (
    ... full query above ...
) AS q
GROUP BY affid