This seems stupid but, I simply need a list of dates to be ordered with the most recent date at top. Using order by DESC doesn't seem to be working the way I want it to.
SELECT *
FROM vw_view
ORDER BY EventDate DESC
It gives me the date ordered by month and day, but doesn't take year into consideration.
for example:
12/31/2009
12/31/2008
12/30/2009
12/29/2009
Needs to be more like:
12/31/2009
12/30/2009
12/29/2009
12/28/2009
and so on.
I'm guessing EventDate is a char or varchar and not a date otherwise your order by clause would be fine.
You can use CONVERT to change the values to a date and sort by that
SELECT *
FROM
vw_view
ORDER BY
CONVERT(DateTime, EventDate,101) DESC
The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.
This means you should either exclude the bad rows or let the bad rows go to the bottom of the results
To exclude the bad rows just add WHERE IsDate(EventDate) = 1
To let let the bad dates go to the bottom you need to use CASE
e.g.
ORDER BY
CASE
WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
ELSE null
END DESC
try ORDER BY MONTH(Date),DAY(DATE)
Try this:
ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
Worked perfectly on a JET DB.
You have the field in a string, so you'll need to convert it to datetime
order by CONVERT(datetime, EventDate ) desc
Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date if SQL Server 2008).
Storing dates as mm/dd/yyyy strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.
what is the type of the field EventDate, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort
If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.
Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format
perhaps using the following
SELECT *
FROM vw_view
ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
Try this
SELECT *
FROM vw_view
ORDER BY DATE_FORMAT(EventDate, "%m-%d-%y") DESC
Related
I'm trying with following query, it is giving me the correct date format but dates are not sorted correctly.
select to_char(date_of_service, 'mm/dd/yyyy') as service_date
from cases
order by service_date
Result I'm getting something like this (sample).
"01/01/2005"
"01/01/2010"
"01/02/2005"
"01/02/2010"
After date format I think it is getting converted into string and due to that sorting is not working. Any alternate solution available for this?
You are sorting by the string value, not the real date value. So you need to change your ORDER BY clause:
select to_char(date_of_service, 'mm/dd/yyyy') as service_date
from cases
order by date_of_service;
Good morning,
I have a datetime column and when I do a SELECT query and ORDER BY the latest date it's returning results from a few weeks ago, which is correct, but when I CONVERT that datetime to a VARCHAR and ORDER BY this new CONVERTED column, it's a date from last year.
Apologies, it's for SQL-Server, here is the query:
SELECT TOP (5) [dbo].[UploadLog].[UploadLogID]
,[dbo].[UploadLog].[ChangedBy]
,CONVERT(VARCHAR(19),[dbo].[UploadLog].[LastChanged]) AS UploadDate
,[dbo].[UploadLog].[CompanyID]
FROM [dbo].[UploadLog]
WHERE [dbo].[UploadLog].[ChangedBy] = '5'
ORDER BY [UploadDate] desc
I'm not sure why this is happening but would appreciate any help.
Many thanks!
I believe your query contains ORDER BY after it converts to VARCHAR. Thats why you're getting the date from last year. You should ORDER BY first then CONVERT the result to VARCHAR. You can use inner queries or other ways to do this.
Btw, if you edit your question and add your query, we could help more effectively.
I am working on creating some reports from data that someone else created the databases for and am having trouble getting proper sorts.
This report is supposed to show the 20 most recent entries, but the data does not include a timestamp, instead it was created using two separate varchar fields, one for the date in the format MM/dd/yyyy and one for the time in the format HH:mm:ss AM/PM. This is causing issues when I try to select the most recent data.
When I use:
SELECT top 20 * FROM SignIn order by Checkin desc, Intime desc
I get the correct date, but the times are the values that start with 9:59am and go down from there alphabetically with 6am immediately after 7pm.
After doing much research I tried, among other things:
SELECT * FROM SignIn order by Checkout desc, CONVERT(varchar(30), outtime, 101) desc
The results were the same.
I don't do much in MS SQL, I am more fluent with with MySql and have never seen any reason to have dates stored as straight strings before. I am at a loss as to getting it to sort correctly.
I have tried creating the report with the html, php, and javascript handling the sort and display instead of having SQL just access the first records, but the load time is ridiculous since it loads the full 5000 pieces of data and then sorts them and clips all but the first 20.
As much as I wish I could, I can't change the database storage at this time, so I need something that will work with the varchars and handle the am\pm distinction if at all possible.
Any help would be appreciated.
You can concatenate the two columns and cast the result as datetime and use it for sorting.
SELECT top 20 *
FROM SignIn
ORDER BY cast(Checkout+' '+outtime as datetime) desc
Note that this assumes all the dates and times are valid. In case you may have incorrect values, use try_cast (for SQL Server versions 2012 and later)
SELECT top 20 *
FROM SignIn
WHERE try_cast(Checkout+' '+outtime as datetime) is not null --invalid values get filtered out
ORDER BY cast(Checkout+' '+outtime as datetime) desc
Just you have to concatenate your date time columns and convert to date like the following:
SELECT * FROM SignIn order by CONVERT(DATETIME, [dateColumn] + ' ' + [TimeColumn], 101) desc
you can learn more about datetime format in this tutorials link
I've written a query to check whether more than one record exists on the same day. Currently the excerpt from my query that performs the restriction looks like this :
GROUP BY
entry_date
HAVING
COUNT(entry_date) > 1
As the entry date column is defined as a datetime, does it check against the full datetime or just the date?
Thanks.
if entry_date is DATETIME ,your group by wont work as expected.you need to CAST it to DATE.Cast(Datetime)to date is sargable as well.
GROUP BY cast(entry_date as DATE)
having count(cast(entry_date as DATE)) > 1
Since you don't cast or convert it to anything else, naturally it uses all data available. So it would group data together with the exact same datetime. Why would you expect anything else?
It should be full datetime.
CONVERT(date, entry_date)
should separate out the date.
I have 10 rows for today's date but my select statement based on date dosen't seem to work....
SELECT Id,WirelessId,RegNo,DriverName1,MobileNo1,DriverName2,MobileNo1 from
DailySchedule where IsDeleted=0 and CreatedDate='2010-05-28'
Any suggestion...
Only if the dates assigned to them are midnight today. It might be better to do:
CreatedDate BETWEEN '2010-05-28 00:00' AND '2010-05-29 00:00'
If you want all the entries for May 28th I would do
and CreatedDate >='20100528'
and CreatedDate < '20100529'
Notice the safe ISO format (YYYYMMDD) no dashes
Also take a look at How Does Between Work With Dates In SQL Server? to see why between can not give you all the results you want
Assuming that CreatedDate is a datetime or a date, I don't see what's wrong with the syntax of the where clause. Maybe the IsDeleted field for those columns is actually NULL? (Or non-zero, at any rate.)
Edit: what Dave says, or DATE(CreatedDate) = '2010-05-28'
I'd check to see the type of the CreatedDate column and make sure that the string you're passing is being converted to a date properly.
When you say you 'have' 10 rows, is that confirmed visually or with a query executed in a console?
Not enough info to go on but I suspect that your dates have a time component and so don't match the string exactly.
Try using:
datediff(day, CreatedDate, '28-may-2010')) = 0
SELECT Id,WirelessId,RegNo,DriverName1,MobileNo1,DriverName2,MobileNo1 from
DailySchedule where IsDeleted=0 and date_format(CreatedDate, "%Y-%m-%d")='2010-05-28'
This should work too
select Id,
WirelessId,
RegNo,
DriverName1,
MobileNo1,
DriverName2,
MobileNo1
from DailySchedule
where IsDeleted=0
and CONVERT(varchar,CreatedDate,101) ='05/28/2010'