I'm trying to convert a date format dd/mm/yyyy to display the total numbers of each month for my query. For ex...
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
23/04/2004 24/04/2004 02/05/2004 05/06/2004
I need it to display:
April - 2 May - 1 June - 1
Any information much appreciated.
You say "a date format dd/mm/yyyy" so let's assume that this is actually a DATE or DATETIME column, and not a CHAR or VARCHAR column. This assumption is necessary because otherwise we cannot use date functions on the column. (Database systems do not store dates internally in dd/mm/yyyy format. Most databases use an integer to store dates, where the integer is the number of days since some base date like December 31, 1899. But I digress.)
To count the number of rows by month, we can do something like this:
select month(datecol) as themonth , count(*) as rows from yourtable group by month(datecol)
This will give the results we want, but they will look like this:
4 2 5 1 6 1
To produce month names instead of month numbers, we will need some sort of translation function. Many database systems include a date function specifically for month names, but if yours doesn't, you can do it with substrings. Just create a string consisting of month names, making sure they all have the same length (9 characters) by padding with blanks as necessary. Then use the month number to index into the string and pull out the monthname as a substring.
Here's an example of this in MySQL syntax (even though MySQL has the MONTHNAME function which could be used for this purpose):
select month(datecol) as themonth , substring( concat(' January' ,' February' ,' March' ,' April' ,' May' ,' June' ,' July' ,' August' ,'September' ,' October' ,' November' ,' December' ) , month(datecol)*9 - 8 , 9 ) as monthname , count(*) as rows from yourtable group by month(datecol) order by month(datecol)
Notice that we're still sorting by the numeric month. This is important if we don't want our results to come out as April, August, December, February...
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.