如何在sql中按月求和?
我有一张这样的桌子如何在sql中按月求和?,sql,sql-server,Sql,Sql Server,我有一张这样的桌子 id Date Amount 1 2016-09-29 09:25:37.000 25.13 2 2016-08-01 17:20:39.000 598.00 3 2016-09-29 09:24:47.000 15.60 4 2016-07-28 17:50:11.000 61.80 5 2016-07-28 17:53:56.000 31.40
id Date Amount
1 2016-09-29 09:25:37.000 25.13
2 2016-08-01 17:20:39.000 598.00
3 2016-09-29 09:24:47.000 15.60
4 2016-07-28 17:50:11.000 61.80
5 2016-07-28 17:53:56.000 31.40
6 2016-07-22 10:40:27.000 74.16
我想得到两个这样的专栏
MonthYear Total
Sep 2016 40.73
Aug 2016 598.00
Jul 2016 167.36
但是,我想把最近的一年和一个月列为榜首。试试这个sql
SELECT CONVERT(CHAR(4), Date, 100) + CONVERT(CHAR(4), Date, 120)
AS MonthYear, SUM(Amount)
AS Total,
CAST(CONVERT(varchar(4), Date, 120) AS int)
AS Year, DATEPART(m, Date) As Month
FROM your_table
GROUP BY CONVERT(CHAR(4), Date, 100) + CONVERT(CHAR(4), Date,120),CAST(CONVERT(varchar(4), Date, 120) AS int), DATEPART(m, Date)
ORDER BY Year DESC, Month DESC
试试下面
SELECT Datename(MONTH, [Date]) month_name,
Year([Date]) year,
Sum([Amount]),
Month([date]) month_no
FROM #Table1
GROUP BY Datename(MONTH, [Date]),
Year([Date]),
Month([date])
ORDER BY Month([date]) DESC,
Year([Date]),
Datename(MONTH, [Date])
只是另一种观点 查询
SELECT t.[MonthYear], SUM(t.[Amount]) AS [Total] FROM(
SELECT RIGHT((CONVERT(VARCHAR(11), [Date], 106)), 8) as [MonthYear], [Amount]
FROM [your_table_name]
)t
GROUP BY t.[MonthYear];
这是一个带有group by/order by语句的普通求和。求和所有金额/数字,对除金额/数字以外的其他数据进行分组,并根据您的选择对其进行相应的显示。