Search code examples
sqlsql-servergroup-bydate-conversionsql-date-functions

How to Convert a Month from INT to VARCHAR when grouping the date by MONTH


I need to summarize number of interviews for each month for all the years in a readable way.

SELECT month(i.Date) AS Month, Year(i.Date) AS Year, Count(i.Id) AS' Number of Interviews'
FROM Interviews i
GROUP BY month(i.Date), year(i.Date)
ORDER BY year(i.Date) DESC, month(Date) ASC

I want the query to return Month as VARCHAR like 'January' instead of default INT from 'month' function.


Solution

  • For MySql it would be:

    SELECT 
      monthname(i.Date) AS Month, 
      Year(i.Date) AS Year, 
      Count(i.Id) AS `Number of Interviews`
    FROM Interviews i
    GROUP BY month(i.Date), monthname(i.Date), year(i.Date)
    ORDER BY year(i.Date) DESC, month(i.Date) ASC
    

    For SQL Server:

    SELECT 
      datename(month, i.date) AS Month, 
      Year(i.Date) AS Year, 
      Count(i.Id) AS [Number of Interviews]
    FROM Interviews i
    GROUP BY month(i.Date), datename(month, i.date), year(i.Date)
    ORDER BY year(i.Date) DESC, month(i.Date) ASC