简体   繁体   中英

SQL: Changing structure of query

I have a query which successfully returns a single value where "day" is hardcoded in the query, as below:

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;

I'm trying to remove this hardcoding such that two columns; namely day:theCount are returned.

I have tried

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;

and it executes. However the values it returns are obviously incorrect (no obvious correlation to the data in the tables being queried)

In the first example, if I am reading this right, you are getting the count of records for day = 0 for each fk_hour value, and selecting the max count from that.

To do this for all days, start by writing an aggregation query to get the count of each day and hour pair like this:

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

Once you have that, you can get the maximum value by using limit 1:

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

This query will return one row, and tell you at which day and which hour the highest number of records occurred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM