我想显示以下内容:
month no. 1 month January total income $xx
一站式“查询”
目前我正在使用下面的代码来显示我想要的输出。但是,我想知道是否可以在一个查询中对其进行编码以显示所需的输出?
当前使用的代码:
DECLARE @january int = 0 SELECT Month(Transaction_Date) AS Month_Number, DATENAME(MONTH, DATEADD(MONTH, @january, 0)) AS 'Month', CONCAT('$', SUM(Credit_Amount)) AS Total_Income FROM Income WHERE Transaction_Date BETWEEN '2020-01-01' AND '2020-01-31' GROUP BY MONTH(Transaction_Date) DECLARE @february int = 1 SELECT Month(Transaction_Date) AS Month_Number, DATENAME(MONTH, DATEADD(MONTH, @february, 0)) AS 'Month', CONCAT('$', SUM(Credit_Amount)) AS Total_Income FROM Income WHERE Transaction_Date BETWEEN '2020-02-01' AND '2020-02-29' GROUP BY MONTH(Transaction_Date) DECLARE @march int = 2 SELECT Month(Transaction_Date) AS Month_Number, DATENAME(MONTH, DATEADD(MONTH, @march, 0)) AS 'Month', CONCAT('$', SUM(Credit_Amount)) AS Total_Income FROM Income WHERE Transaction_Date BETWEEN '2020-03-01' AND '2020-03-31' GROUP BY MONTH(Transaction_Date) DECLARE @april int = 3 SELECT Month(Transaction_Date) AS Month_Number, DATENAME(MONTH, DATEADD(MONTH, @april, 0)) AS 'Month', CONCAT('$', SUM(Credit_Amount)) AS Total_Income FROM Income WHERE Transaction_Date BETWEEN '2020-04-01' AND '2020-04-30' GROUP BY MONTH(Transaction_Date)
您可以按EOMONTH月份的最后一天分组
SELECT Month(EOMONTH(Transaction_Date)) AS Month_Number, DATENAME(MONTH, EOMONTH(Transaction_Date)) AS [Month], CONCAT('$', SUM(Credit_Amount)) AS Total_Income FROM Income WHERE Transaction_Date >= '2020-01-01' AND Transaction_Date < '2020-05-01' GROUP BY EOMONTH(Transaction_Date);