It returns all rows sorted by CountOfRecords DESC. I’d like to have just seven rows here, showing the highest value ever for the specified day. So each day of the week should occur once and only once. Is this possible without a lot of pain?
SELECT
Count(*) As CountOfRecords,
CAST(FLOOR(CAST([visit].[datetimeentered] AS float)) AS smalldatetime) AS DateEntered,
DatePart(dw, visit.datetimeentered) As DayOfTheWeek
FROM visit
INNER JOIN useragent ON useragent.useragentid = visit.useragentid
WHERE useragent.isbot = 0
GROUP BY CAST(FLOOR(CAST([visit].[datetimeentered] AS float)) AS smalldatetime),
DatePart(dw, visit.datetimeentered)
ORDER BY CountOfRecords DESC
Edit1:
I think both answers are getting at the same thing. I’ve accepted the one that was posted first. I’m also going to mention that it worked right off the bat while the other did not. I’m getting the following errors when I run marc_s’s query:
Msg 207, Level 16, State 1, Line 29
Invalid column name 'RowNum'.
Msg 207, Level 16, State 1, Line 25
Invalid column name 'CountOfRecords'.
Msg 207, Level 16, State 1, Line 26
Invalid column name 'DateEntered'.
Msg 207, Level 16, State 1, Line 27
Invalid column name 'DayOfTheWeek'.
Special thanks to marc_s for pointing out a simple way to get the only the date portion from a datetime.
Based on your query:
This will return one row for each day of week represented in the table. If there may be duplicates by
CountOfRecordsamong the maximum values and you want to return them all, useRANK()instead ofROW_NUMBER().