首先,让我们获取一个查询来将数据处理成更易于使用的东西:
SELECT ID, 0 AS dow, 8 as hr, `8AM` AS hits
FROM SUNDAY
UNION ALL
SELECT ID, 0 AS dow, 9 as hr, `9AM` AS hits
FROM SUNDAY
UNION ALL
SELECT ID, 0 AS dow, 10 as hr, `10AM` AS hits
FROM SUNDAY
UNION ALL
SELECT ID, 0 AS dow, 11 as hr, `11AM` AS hits
FROM SUNDAY
UNION ALL
SELECT ID, 1 AS dow, 8 as hr, `8AM` AS hits
FROM MONDAY
UNION ALL
SELECT ID, 1 AS dow, 9 as hr, `9AM` AS hits
FROM MONDAY
UNION ALL
SELECT ID, 1 AS dow, 10 as hr, `10AM` AS hits
FROM MONDAY
UNION ALL
SELECT ID, 1 AS dow, 11 as hr, `11AM` AS hits
FROM MONDAY
UNION ALL
SELECT ID, 2 AS dow, 8 as hr, `8AM` AS hits
FROM TUESDAY
UNION ALL
SELECT ID, 2 AS dow, 9 as hr, `9AM` AS hits
FROM TUESDAY
UNION ALL
SELECT ID, 2 AS dow, 10 as hr, `10AM` AS hits
FROM TUESDAY
UNION ALL
SELECT ID, 2 AS dow, 11 as hr, `11AM` AS hits
FROM TUESDAY
返回的数据的 SQL Fiddle 示例
然后你可以从这个(派生的)表中选择:
SELECT ID, SUM(hits) AS hits
FROM
(
--above query, either as a view or derived table
--or permanently changed
) hitsTable
WHERE (dow = 0 AND hr IN (9,11))
OR (dow = 1 AND hr IN (10,11))
OR (dow = 2 AND hr = 9)
GROUP BY ID
ORDER BY SUM(hits) DESC
SQL 小提琴示例
WHERE
请注意此处子句的简单性。如果您可以控制您的架构,我建议您永久更改数据存储为此格式的方式。它会让你的生活更轻松。如果你不能,我建议至少制作一个以这种方式组合所有表的视图,这样你就可以轻松地查询它们。
你能用你当前的模式来做吗?当然,它可能看起来“更短”或“更简单”,但如果您动态构建这些查询,它就不那么漂亮了:
SELECT ID, SUM(hits) AS hits
FROM
(
SELECT ID, `9AM` + `11AM` AS hits
FROM SUNDAY
UNION ALL
SELECT ID, `10AM` + `11AM` AS hits
FROM MONDAY
UNION ALL
SELECT ID, `9AM` AS hits
FROM TUESDAY
) x
GROUP BY ID
ORDER BY SUM(hits) DESC