虽然您将无法动态创建列,但您可以“伪造”它们并UNION
为每个日期范围使用 a。在每个中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