简体   繁体   English

SQL Query从数据库中检索月份名称

[英]SQL Query to retrieve month name from database

I've following query, what i want to do is, i just want month name from the date column, in the following query its displaying month number 我跟着查询,我想要做的是,我只想从日期列中查看月份名称,在下面的查询中显示月份编号

SELECT MONTH(Invoice_Date), SUM(R.Total) AS TOTAL
FROM Sales R
GROUP BY MONTH(Invoice_Date)
ORDER BY MONTH(Invoice_Date);

I tried MonthName function, also i tried convert function but neither one is working. 我尝试了MonthName函数,我也试过转换函数,但没有一个工作。 Following error is displayed Undefined Function. 显示以下错误未定义的功能。 Please Help, Thanks 请帮助,谢谢

Try datepart function of MS SQL http://msdn.microsoft.com/en-us/library/ms174420.aspx 尝试MS SQL的datepart函数http://msdn.microsoft.com/en-us/library/ms174420.aspx

MS sql query will be: MS sql查询将是:

SELECT 
  DATEPART(month,Invoice_Date), 
  SUM(R.Total) AS TOTAL 
FROM Sales R 
GROUP BY DATEPART(month,Invoice_Date) 
ORDER BY DATEPART(month,Invoice_Date)

Assuming that Invoice_Date "Is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable, or string literal." 假设Invoice_Date“是一个可以解析为time,date,smalldatetime,datetime,datetime2或datetimeoffset值的表达式.date可以是表达式,列表达式,用户定义变量或字符串文字。”

Assuming that you use MS Access only and not SQL Server and therefore can't use T-SQL functions one way to do this is to use the switch function like this: 假设您只使用MS Access而不使用SQL Server,因此不能使用T-SQL函数,一种方法是使用这样的switch函数:

SELECT SWITCH( 
  MONTH(invoice_date) = 1, "January", 
  MONTH(invoice_date) = 2, "February", 
  MONTH(invoice_date) = 3, "March"
  MONTH(invoice_date) = 4, "April"
  MONTH(invoice_date) = 5, "May"
  MONTH(invoice_date) = 6, "June"
  MONTH(invoice_date) = 7, "July"
  MONTH(invoice_date) = 8, "August"
  MONTH(invoice_date) = 9, "September"
  MONTH(invoice_date) = 10, "October"
  MONTH(invoice_date) = 11, "November"
  MONTH(invoice_date) = 12, "December"
) AS MonthName, SUM(R.Total) AS TOTAL

FROM Sales R
GROUP BY MONTH(Invoice_Date)
ORDER BY MONTH(Invoice_Date);

Another option would be to create a table containing month names and number and retrieve the name from that via a join. 另一种选择是创建一个包含月份名称和数字的表,并通过连接从中检索名称。

Yes, using T-SQL it is possible to get the month name from month number of a date. 是的,使用T-SQL可以从日期的月份编号获取月份名称。

SELECT DATENAME(month, DATEADD(month, MONTH(Invoice_Date), 0 ) -1);

Then, your final query will look like this: 然后,您的最终查询将如下所示:

SELECT MONTH(Invoice_Date), DATENAME(month, DATEADD(month, MONTH(Invoice_Date), 0 ) -1) as MonthName, SUM(R.Total) AS TOTAL
FROM Sales R
GROUP BY MONTH(Invoice_Date)
ORDER BY MONTH(Invoice_Date);

try this 尝试这个

SELECT DATENAME(month, Invoice_Date), SUM(R.Total) AS TOTAL
FROM Sales R
GROUP BY DATENAME(month, Invoice_Date)
ORDER BY DATENAME(month, Invoice_Date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM