SQL:更改查询结构

时间:2015-07-08 18:25:12

标签: mysql sql subquery

我有一个成功返回单个值的查询,其中" day"在查询中是硬编码的,如下所示:

SELECT MAX(theCount) FROM
    (SELECT FK_Hour, Count(FK_Hour) As theCount FROM
        (Select FK_Hour
        From slottime
        INNER JOIN time ON slottime.FK_Hour = time.Hour
        WHERE FK_Hour IN 
            (SELECT time.Hour FROM time WHERE time.day=0 )
        ) As C
        GROUP By FK_Hour
    ) AS counts;

我试图删除这两个列的硬编码;亦即 day:返回theCount。

我试过了

SELECT MAX(theCount), day FROM
(SELECT FK_Hour, day As day, Count(FK_Hour) As theCount FROM
    (Select slottime.FK_Hour, time.day
    From slottime
    INNER JOIN time ON slottime.FK_Hour = time.Hour
    ) As C
    GROUP By FK_Hour
) AS counts
GROUP By day;

然后执行。但是它返回的值显然是不正确的(与被查询的表中的数据没有明显的相关性)

1 个答案:

答案 0 :(得分:0)

在第一个示例中,如果我正在读取此权限,则您将获得每个fk_hour值的day = 0记录计数,并从中选择最大计数。

要在所有日子里执行此操作,请首先编写一个聚合查询,以获取每天和每小时对的计数:

SELECT t.day, t.hour, COUNT(*) AS numRecords
FROM time t
GROUP BY t.day, t.hour;

完成后,您可以使用限制1:

获得最大值
SELECT t.day, t.hour, COUNT(*) AS numRecords
FROM time t
GROUP BY t.day, t.hour
ORDER BY COUNT(*) DESC
LIMIT 1;

此查询将返回一行,并告诉您哪一天和哪个小时发生了最大数量的记录。