Mysql sort date format - mysql

I have an unavoidable situation where the dates are stored in UK date format, e.g.:
31/12/2001 00:00:00
I need it in descending order, I've tried this but it errors
select *, DATE_FORMAT(completiondate,'\%e/%c/%Y\') as cdate
from projects
where countries = 1
order by cdate desc
Error:
check the manual that corresponds to your MySQL server version for the
the right syntax to use near '' order by cdate desc'
I'm using MySQL 4.1.9

This was the end solution
select *,completiondate from projects order by str_to_date(completiondate,'%d/%m/%Y %H:%i') desc

You are escaping the % character unnecessarily. But the actual problem is that that you have an un-terminated string literal in your query:
-- this does not terminate the string ----------v
select *, DATE_FORMAT(completiondate,'\%e/%c/%Y\') as cdate
from projects
where countries = 1
order by cdate desc
Change to:
SELECT *, DATE_FORMAT(completiondate,'%e/%c/%Y') AS cdate
FROM projects
WHERE countries = 1
ORDER BY cdate DESC

Jim, your end solution was a huge help for me. My dates are in the 02/28/2013 format. I used the code:
SELECT *,str_to_date(SaleDate,'%m/%d/%Y') AS cdate FROM mytable ORDER BY cdate DESC
Thanks!

SELECT * FROM projects WHERE countries = 1 order by cdate desc
I'm guessing you have cdate already in your database? If so, you don't need to set "date_format" since it's already there.
But I may be wrong since I've never used 4.1.9

Related

How to sort by date in mysql

I need to perform the following query in mysql.
SELECT
evaluationpart.id,
evaluationpart.creation,
evaluationpart.evaluationid,
evaluationpart.partid,
evaluation.horimeter,
personcompressorpart.hourcapacity,
evaluation.evaluationdate AS changedate,
evaluation.averageworkload,
#ed := DATEDIFF(curdate(), evaluation.evaluationdate) AS elapseddays,
#uh:= #ed * evaluation.averageworkload AS usedhours,
#htu:= personcompressorpart.hourcapacity - #uh AS hourstouse,
#nc:= curdate() + INTERVAL (#htu/evaluation.averageworkload) DAY AS nextchange
FROM evaluationpart
LEFT JOIN evaluation ON evaluation.id = evaluationpart.evaluationid
LEFT JOIN personcompressorpart ON personcompressorpart.id = evaluationpart.partid
ORDER BY #nc ASC
But the Order By is not working and I'm getting this result
Could anyone tell me why?
It seems that you are not using the column name in the ORDER BY clause.
If you want to order the query result by the column named 'nextchange', the ORDER BY clause should be ORDER BY nextchange ASC.
Here's the MySQL documentation on Sorting Rows: https://dev.mysql.com/doc/refman/8.0/en/sorting-rows.html
I hope this helps.

mysql date conversion returns null converting certain months

I have this query (take a look on between dates):
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between (STR_TO_DATE('11/24/2020','%m/%d/%y'))
and (STR_TO_DATE('12/26/2021','%m/%d/%y'))
GROUP BY user_name ;
The select is between dates:
startDate: (STR_TO_DATE('11/24/2020','%m/%d/%y'))
finishDate: (STR_TO_DATE('12/26/2021','%m/%d/%y'))
This query will return something because there are records on year 2020
the problem is when i change the month of the finishDate, i tried with:
finishDate: (STR_TO_DATE('1/26/2021','%m/%d/%y')) = null
finishDate: (STR_TO_DATE('01/26/2021','%m/%d/%y')) = null
finishDate: (STR_TO_DATE('10/26/2021','%m/%d/%y')) = null
It just makes no sense... im using mysql community 8.0.20
Since the problem only occurs in the finsihDate perhaps this could be helpful.
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between (STR_TO_DATE('11/24/2020','%m/%d/%y'))
and (DATE_ADD(STR_TO_DATE('11/24/2020','%m/%d/%y'), INTERVAL 367 DAY))
GROUP BY user_name ;
Of course you should check for relevant errors or warnings in MySQL server logs, that could explain the problem for finsihDate.
********UPDATE SOLUTION:
for some unknown reason my db IDE shows the date with this format "$DAY/$MONTH/$YEAR" even if insert the right DATE MYSQL FORMAT ("$YEAR-$MONTH-$DAY)
i got the following warnings:
And this is the final query that worked but your solution did worked as well:
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between '2020-11-24' AND '2021-01-24'
GROUP BY user_name ;
The problem with your query is the date format. Lowercase '%y' matches a two digit year. So, only the first two characters from 2021 are used for the year -- and you have the wrong year.
But, that is not the real problem. You don't need str_to_date(). Just use properly formatted date literals.
Assuming that the dates are stored correctly as date data types, then you can simply use:
SELECT user_name, COUNT(*) AS COUNT
FROM user_records
WHERE date_created between '2020-11-24' and '2021-12-26'
GROUP BY user_name ;
If date_created is stored as a string, then fix your data model so it is either a date or datetime. Dates should not be stored as strings.

how to use DISTINCT ON with mysql using ActiveRecord

Want all the latest visit of all the distinct user.
For this I am using below query
Event.order(time: :desc).select('DISTINCT ON(user_id) user_id, time')
Getting SQL syntax error.
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC ' at line 1: SELECT DISTINCT ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC LIMIT 11)
events table column names
["id", "visit_id", "user_id", "name", "properties", "time"]
can anyone help me out in this
Expected output something like this
{ 21 => "2018-12-18 09:44:59", 42 => "2018-12-19 12:08:59"}
21 is user_id and value is last visit time
Using mysql as database
So you want all user visits with last visited time.
Instead of use DISTINCT function, you can use GROUP with MAX function.
Query looks like
Events.group(:user_id).maximum(:time)
This Outputs your desired results
{21=>Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23=>Thu, 20 Dec 2018 06:42:10 UTC +00:00}
Hope this works for you.
FYI
DISTINCT ON(columns). is PostgreSQL Syntax.
Like i said in the comments DISTINCT ON(column), * is PostgreSQL SQL syntax.
The query below you need to have to rewrite in MySQL
SELECT
DISTINCT ON(user_id) AS user_id, time
FROM
<table>
ORDER BY
time DESC
LIMIT 11
The most easy to do that is using SUBSTRING_INDEX(GROUP_CONCAT(..)).
The queries below should give you the correct results.
SET SESSION group_concat_max_len = ##max_allowed_packet;
SELECT
user_id
, SUBSTRING_INDEX(
GROUP_CONCAT(time
ORDER BY
time DESC
)
, ','
, 1
) AS time
FROM
<table>
GROUP BY
user_id
ORDER BY
time DESC
LIMIT 11

SQL time column does not sort in ascending order

I was having some trouble when trying to write an SQLstatement which sorted by time column which is in varchar format in ascending order. Here is my SQL statement:
SELECT mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY mrtpopTime
And I am getting these results:
As you can see from the picture, it was sorted by character by character. Is there anyway to sort it like:
0:00, 1:00, 2:00, 3:00 all the way to 23:00
Any ideas? Thanks in advance.
Convert varchar time column to a time (or dummy date plus time) and order by that:
SELECT mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY STR_TO_DATE(mrtpopTime, '%H:%i')
As the mrtpopTime is in varchar it won't sort. Hence cast it into float and order by
SELECT mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY 'cast(mrtpopTime as float) time'

How to sort mmm-yyyy date format in mysql

I have column its format is mmmm-yyyy for a eg. 'March-2013'
How to sort that column by date order....
I have tried with ORDER by desc
but its is sorting by Alphabetically... please help me
You can use str_to_date to convert the string to a date:
SELECT *
FROM my_table
ORDER BY STR_TO_DATE(my_field, '%M-%Y') DESC
If you are using aggregation, you can do something like:
order by min(col) desc
If not, you can convert to a date:
order by str_to_date(concat('01-', col), '%d-%M-%Y')
Strictly speaking you don't need the 01, but I'm uncomfortable with MySQL's incomplete dates.
SELECT * FROM articles ORDER BY time DESC