0

I have a mysql column where the data is stored as VARCHAR though the data values are of datetime in the format of yyyy-mm-dd hh:mm:ss. Now my task is to group by the date part i.e yyyy-mm-dd by converting VARCHAR to date-time and then just taking date part out of it

QUERY

SELECT SUM(value) 
FROM table 
GROUP BY name , [date part of the varchar field]

Please let me know if this is at all possible and if yes, how?

0

2 Answers 2

2

Assuming that your data in this varchar field is properly formatted, you can work with the left function, like this:

SELECT LEFT(mydate, 10) AS myval, 
       SUM(myvalue)
FROM   mytable
GROUP BY myval;

If this isn't a big issue; I'd advise converting your varchar column to datetime or timestamp. If not only for the possibly better data storage usage, it'll be way easier to do work with date and time related functions.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Bjoem , shall i store date and time as same fields or seperate fields and if seperate, what would be the datatype of each of them (or both would have same data type of datetime) ?
That depends on what you want to do with the data. In my applications I usually have to calculate with those fields, therefore datetime is mostly my choice. Read about this here and make up your mind. dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html
1

Just use the left function. You can leave the date as a string:

SELECT left(datecol, 10) as YYYYMMDD, SUM(value)
FROM table
GROUP BY left(datecol, 10);

I removed name from the group by because it doesn't seem relevant to the question. You can, of course, add it back in.

By the way, MySQL understands this format for dates, so if you really, really want a date:

SELECT date(left(datecol, 10)) as RealDate, SUM(value)
FROM table
GROUP BY RealDate;

1 Comment

this works as expected, i included name column in select, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.