我有几个结构完全相同的表。它们包含来自年度活动入口处填写的表格的数据。这些表中的一个字段是DATETIME
条目的日期和时间。
出于统计目的,我试图比较每年每小时的条目数量。当然,我可以为每个表运行单独的查询并在 PHP 中将它们放在一起。但我认为在一个查询中也应该可以。但是,我无法弄清楚如何建立正确的查询。
这是我到目前为止所得到的:
SELECT
WEEKDAY(P3.AddedOn) Day,
HOUR(P3.AddedOn) Hour,
COUNT(P3.AddedOn) Entries2013,
COUNT(P2.AddedOn) Entries2012
FROM Event2013 P3
LEFT JOIN Event2012 P2
ON WEEKDAY(P3.AddedOn) = WEEKDAY(P2.AddedOn)
AND HOUR(P3.AddedOn) = HOUR(P2.AddedOn)
GROUP BY WEEKDAY(P3.AddedOn), WEEKDAY(P2.AddedOn), HOUR(P3.AddedOn), HOUR(P2.AddedOn)
但是这个查询会产生一些奇怪的结果,其中的数字太大并且 Entries2012 和 Entries2013 列中的数字相同。它增加了一些数据,但我无法弄清楚究竟是哪个。
我究竟做错了什么?
谢谢您的帮助!
--
用子查询解决:
SELECT
P2.Day,
P2.Hour,
P2.Entries Entries2012,
P3.Entries Entries2013
FROM
(
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2012
GROUP BY Day, Hour
) P2
LEFT JOIN
(
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2013
GROUP BY Day, Hour
) P3
ON P2.Day = P3.Day
AND P2.Hour = P3.Hour
--
现在还有某种 MySQL FULL OUTER JOIN:
SELECT
Day,
Hour,
Entries2012,
Entries2013
FROM (
SELECT
(CASE P2.Day
WHEN 4 THEN "Fr"
WHEN 5 THEN "Sat"
WHEN 6 THEN "Sun"
ELSE P2.Day
END) AS Day,
P2.Hour,
COALESCE(P2.Entries, 0) Entries2012,
COALESCE(P3.Entries, 0) Entries2013
FROM (
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2012
GROUP BY Day, Hour) P2
LEFT JOIN (
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2013
GROUP BY Day, Hour) P3
ON P2.Day = P3.Day
AND P2.Hour = P3.Hour
UNION SELECT
(CASE P3.Day
WHEN 4 THEN "Fr"
WHEN 5 THEN "Sat"
WHEN 6 THEN "Sun"
ELSE P3.Day
END) AS Day,
P3.Hour,
COALESCE(P2.Entries, 0) Entries2012,
COALESCE(P3.Entries, 0) Entries2013
FROM (
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2012
GROUP BY Day, Hour) P2
RIGHT JOIN (
SELECT
WEEKDAY(AddedOn) Day,
HOUR(AddedOn) Hour,
COUNT(1) AS Entries
FROM Event2013
GROUP BY Day, Hour) P3
ON P2.Day = P3.Day
AND P2.Hour = P3.Hour
WHERE P2.Hour IS NULL) AS tmp
ORDER BY Day, Hour