首页 > 解决方案 > 按 MONTH 分组日期时如何将月份从 INT 转换为 VARCHAR

问题描述

我需要以一种可读的方式总结这些年来每个月的采访次数。

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

我希望查询以 VARCHAR 形式返回 Month,例如 'January' 而不是来自 'month' 函数的默认 INT。

标签: sqlsql-servergroup-bydate-conversionsql-date-functions

解决方案


对于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 服务器

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

推荐阅读