I couldn't find a solution for this and also my SQL skills are very poor, so maybe someone can advise if the following is possible.
Environment: Microsoft SQL Server 2008 R2
The current query is very simple, selecting the values of error codes, counting the number of errors and grouping on the error codes:
- EC - ErrorCode (there are arround 200 different error codes)
- NoEr - count(*) as NoEr (some days the error count can be empty)
Query:
SELECT
ErrorCode AS EC, COUNT(*) as NoEr
FROM
[DB].[dbo].[Table]
WHERE
ERRORTIME > '2018-12-30 00:00:00'
AND ERRORTIME < '2018-12-30 23:59:59'
GROUP BY
errorcode
ORDER BY
ERRORCODE ASC
Output:
+----+-------+
| EC | NoEr |
+----+-------+
| A9 | 3333 |
| E0 | 1505 |
| G9 | 1233 |
| X1 | 2 |
+----+-------+
I would like to obtain the count of errors for the last 5 days displayed as per below:
+----+-------+-------+-------+-------+-------+
| EC | MON | TUE | WED | THU | FRI |
+----+-------+-------+-------+-------+-------+
| A9 | 1505 | 2333 | | 1555 | 9999 |
| E0 | 3333 | | 2311 | 5555 | 14 |
| G9 | 2222 | 1505 | 123 | 1233 | |
| X1 | 1212 | 1233 | 1155 | 3 | |
+----+-------+-------+-------+-------+-------+
Thank you & have a great new year !
You can us
CASE
expression along with aggregateSUM
to calculate the count for each weekday like below -You could use pivot operator to achieve your goal.
Best Regards,
Will
You want the results for the last five days, not for a single day, so I think you want:
Note that when you use functions such as
DATEADD()
andDATENAME()
you should not use abbreviations. That is just a bad query-writing habit. No one want to have to remember whetherw
means "week" or "weekday" or whetherm
means "minute" or "month". Use the full name and eschew ambiguity.If you like you can also simplify this to:
Like Will he said the best option is to use the PIVOT: