按MONTH分组日期时如何将月份从INT转换为VARCHAR

时间:2019-04-28 20:37:20

标签: sql group-by date-conversion sql-date-functions group-summaries

我需要以一种可读的方式总结多年来所有月份中每个月的采访次数。

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

我希望查询以类似于“ January”的VARCHAR形式返回Month,而不是“ month”函数的默认INT。

3 个答案:

答案 0 :(得分:1)

对于 MySql ,它是:

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

对于 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

答案 1 :(得分:0)

适用于大多数DBMS的解​​决方案是CASE表达式。

SELECT CASE month(i.date)
         WHEN 1 THEN
           'January'
         ...
         WHEN 12 THEN
           'December'
       END month,
       year(i.date) year,
       count(i.id) number_of_interviews
       FROM interviews i
       GROUP BY month(i.date),
                year(i.date)
       ORDER BY year(i.date) DESC,
                month(i.date) ASC;

答案 2 :(得分:0)

SELECT count(1),格式(dateColumn,“ yyyy-MM”) FROM tableName GROUP BY格式(dateColumn,“ yyyy-MM”) 按2排序