1

我想要做的是选择所有匹配最多的 ID,并按点击次数最多的顺序列出它们

表 - 星期日

身份证 | 上午 8 点 | 上午 9 点 | 上午 10 点 | 上午11点
一个 | 0 | 1 | 0 | 0
乙| 0 | 0 | 1 | 1
C | 0 | 0 | 0 | 1

表 - 星期一

身份证 | 上午 8 点 | 上午 9 点 | 上午 10 点 | 上午11点
一个 | 0 | 0 | 1 | 1
乙| 0 | 1 | 0 | 0
C | 0 | 0 | 0 | 1

表 - 星期二

身份证 | 上午 8 点 | 上午 9 点 | 上午 10 点 | 上午11点
一个 | 0 | 1 | 0 | 0
乙| 0 | 1 | 0 | 0
C | 0 | 0 | 0 | 1

例如:我想查找所有具有周日上午 9 点和 11 点、周一上午 10 点和 11 点以及周二上午 9 点的 ID,然后按点击次数最多排序

我会得到以下回报。

  • A 4 次命中
  • B 2 次安打
  • C 2 次命中
4

1 回答 1

0

首先,让我们获取一个查询来将数据处理成更易于使用的东西:

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
于 2013-03-21T01:21:11.610 回答