I have a table as follows:
Table: student_test_records
Student TestDate Result
------- ------------------ -------
A 2015-01-26 17:28:11 Pass
B 2015-01-24 17:28:11 Fail
C 2015-01-26 17:28:11 Pass
D 2015-01-26 17:28:11 Fail
E 2014-05-23 17:28:11 Pass
F 2013-06-23 17:28:11 Pass
G 2014-05-23 17:28:11 Fail
I am attempting to write a query in SQL Server to display the number of passed/failed results per day in the following format:
FormattedDate Result Count
----------- ------ -----
May-23-2013 Pass 1
May-23-2014 Fail 1
May-23-2014 Pass 1
Jan-24-2015 Fail 1
Jan-26-2015 Fail 1
Jan-26-2015 Pass 2
The following is the query I attempted:
SELECT FORMAT(TestDate, 'MMM-dd-yyyy') as FormattedDate, Result, Count
FROM student_test_records
GROUP BY FORMAT(TestDate, 'MMM-dd-yyyy'), Result
order BY FORMAT(TestDate, 'MMM-dd-yyyy');
The result set is correct, but the ordering comes by formatted date string (month-day-year alphabetically). How do I order the result on actual date (TestDate)? In MySQL, I could have done ORDER BY TestDate
instead of the last line in the above query.
This should work:
SELECT
FORMAT(cast(TestDate as date), 'MMM-dd-yyyy') as FormattedDate,
Result,
Count(*) as Count
FROM student_test_records
GROUP BY cast(TestDate as date), Result
ORDER BY cast(TestDate as date);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With