SQL Server Return top 3 hours of day with the most activity?

x8diyxa7  于 2023-03-17  发布在  其他
关注(0)|答案(2)|浏览(126)

I have a table that lists day of week, hour of day, and visits.

Sample table:

**Visits   Day  Hour**
83  Thursday 12AM
75  Friday  1AM
124 Tuesday 2AM
0   Sunday 3AM
0   Thursday 4AM
26  Friday  5AM
0   Monday  6AM
7   Friday  7AM
55  Friday  8AM
21  Wednesday 9AM
154 Friday  10AM
425 Thursday 11AM
270 Tuesday 12PM
373 Friday  1PM
0   Friday  2PM
0   Tuesday 3PM
0   Friday  4PM
1774    Tuesday 5PM
509 Friday  6PM
519 Saturday 7PM

I'm trying to show show the top three hours of each weekday (Sunday to Monday) with the highest visits (on average)

An example of what the result should look like:

**Day      Hour      Visits
**
Monday     4PM        xxx
Monday     5PM        xxx
Monday     8PM        xxx
Tuesday    6PM        xxx
Tuesday    7PM        xxx
Tuesday    8PM        xxx

etc

Here's what I tried.

SELECT TOP 3
    [Day],
    [Hour],
    MAX(Visits)
FROM 
    (  SELECT 
    [Day],
    [Hour],
    AVG(Visits) AS Visits
  FROM TableA
  GROUP BY [Day], [Hour]
    ) z
GROUP BY [Day],[Hour]
qmelpv7a

qmelpv7a1#

Try this:

DROP TABLE IF EXISTS #tempVisits;

CREATE TABLE #tempVisits (
    Visits INT,
    Day VARCHAR(10),
    Hour VARCHAR(5)
);

INSERT INTO #tempVisits (Visits, Day, Hour)
VALUES
    (83, 'Thursday', '12AM'),
    (75, 'Friday', '1AM'),
    (124, 'Tuesday', '2AM'),
    (0, 'Sunday', '3AM'),
    (0, 'Thursday', '4AM'),
    (26, 'Friday', '5AM'),
    (0, 'Monday', '6AM'),
    (7, 'Friday', '7AM'),
    (55, 'Friday', '8AM'),
    (21, 'Wednesday', '9AM'),
    (154, 'Friday', '10AM'),
    (425, 'Thursday', '11AM'),
    (270, 'Tuesday', '12PM'),
    (373, 'Friday', '1PM'),
    (0, 'Friday', '2PM'),
    (0, 'Tuesday', '3PM'),
    (0, 'Friday', '4PM'),
    (1774, 'Tuesday', '5PM'),
    (509, 'Friday', '6PM'),
     (519 , 'Saturday', '7PM');

SELECT *
FROM
(
    SELECT  *
          ,ROW_NUMBER() OVER (PARTITION BY [Day] ORDER BY [Visits] DESC) x
    FROM #tempVisits
) DS
WHERE X <= 3
ORDER BY [Day], [Visits] DESC, [Hour] -- or [x]

gopyfrb3

gopyfrb32#

To show only the top three hours of each weekday, you can modify the query as follows

Query:

SELECT [DAY], Hour, VisitsAvg
FROM (
    SELECT Day, Hour, AVG(Visits) as VisitsAvg,
           ROW_NUMBER() OVER (PARTITION BY Day ORDER BY AVG(Visits) DESC) as RowNumber
    FROM #tempVisits 
    GROUP BY Day, Hour
) as t
WHERE t.RowNumber <= 3
ORDER BY Day, VisitsAvg DESC

相关问题