Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order by a date in string format properly?

I have a table with the following fields in an SQL Server 2005 database:

  • id, integer
  • value, string
  • create_date, datetime

New data is constantly being inserted into this table (tens of thousands of records per day) so I use the following query to compare how much data has been inserted on different days.

SELECT CONVERT(varchar(10), create_date, 101) as 'Date', COUNT(*) as 'Record Count',
FROM the_table
GROUP BY CONVERT(varchar(10), create_date, 101)
ORDER BY 'Date' desc

This query returns data looking like this:

12/20/2012 | 48155
12/19/2012 | 87561
12/18/2012 | 71467

However, when running this query today, I noticed the sorting did not work as expected with multiple years worth of data in the database. Instead of the data for this year being at the very top of the result set, it ended up at the bottom (records omitted for clarity)

06/29/2012 | 9987
01/04/2013 | 15768
01/03/2013 | 77586
01/02/2013 | 23566

I understand why this is happening, as my formatted date is simply a string, and sql server can't possibly be expected to sort it as anything but a string. But I would like the ordering to be accurate. How can I achieve this? (the most recent day always appearing first)

like image 419
Mansfield Avatar asked Jan 04 '13 19:01

Mansfield


People also ask

How do I sort dates in string format?

Show activity on this post. ArrayList<String> datestring=new ArrayList<String>(); datestring. add("01/21/2013 @03:13 PM"); datestring. add("01/21/2013 @04:37 PM"); datestring.

How do you order by date?

Here's how to sort unsorted dates: Drag down the column to select the dates you want to sort. Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

What is string date/time format?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.


2 Answers

Thanks to Oded's suggestion I changed my order by clause and this seems to give me what I want:

SELECT CONVERT(varchar(10), create_date, 101) as 'Date', COUNT(*) as 'Record Count',
FROM the_table
GROUP BY CONVERT(varchar(10), create_date, 101)
ORDER BY MIN(create_date) desc
like image 172
Mansfield Avatar answered Nov 01 '22 12:11

Mansfield


You can include the date as a date data type in the GROUP BY and then use it in the ORDER BY

SELECT top 100 CONVERT(varchar, create_date, 101) as 'Date', COUNT(*) as 'Record Count'
FROM constituent
GROUP BY CONVERT(varchar, create_date, 101), CONVERT(date, create_date)
ORDER BY CONVERT(date, create_date)
like image 34
bobs Avatar answered Nov 01 '22 12:11

bobs