SQL如何为报表计算每月数量总和
我有这样的桌子SQL如何为报表计算每月数量总和,sql,Sql,我有这样的桌子 PartID Quantity Date 12315 1 2017-01-24 51245 3 2017-01-26 12345 4 2017-02-20 12415 1 2017-02-25 ..... .. ........... 我需要报告结果,如: Monthly Quantity January: 4 Monthly Quantity February:
PartID Quantity Date
12315 1 2017-01-24
51245 3 2017-01-26
12345 4 2017-02-20
12415 1 2017-02-25
..... .. ...........
我需要报告结果,如:
Monthly Quantity January: 4
Monthly Quantity February: 5
因此,在我的报告中,每一列都应该有月份的名称,并包括本月的所有数量(计数)。如有任何帮助,我们将不胜感激。我想您正在寻找以下问题:
select month(Date), sum(Quantity)
from table
group by month(Date)
您正在使用哪个数据库 在SQL Server上:
选择
日期名称(月份、日期)为“月份名称”,总和(数量)
从桌子上
按日期名称分组(月份、日期)
您可以有两个选项:
1) 创建另一列并在其中存储月份名称
PartID Quantity Date. Month
12315 1 2017-01-24. January
51245 3 2017-01-26. January
12345 4 2017-02-20. February
12415 1 2017-02-25. February
并根据需要使用以下查询获取报告:
Select sum(Quantity) as total_quantity, Month from table group by Month
2) 通过使用MySQL内置的日期和时间函数
Select sum(Quantity) as total_quantity, Month(Date) as month from table group by Month(Date)
在MS SQL中:
您可以使用以下内容:
DATENAME()函数以字符串值的形式返回给定日期的指定部分
要了解有关DATENAME()的更多信息,请访问
CAST()函数将表达式从一种数据类型转换为另一种数据类型
要了解有关CAST()的更多信息,请访问
因此,输出将是
下面回答了一个类似的问题:您需要用RDBMSI标记您的问题,因为我正在使用MS SQL
SELECT
MONTH(Date) AS MonthNo,
'Monthly Quantity ' + DATENAME(MONTH, date) + ' : ' + CAST(SUM(Quantity) AS nvarchar(10)) AS Monthwise
FROM parttable
GROUP BY DATENAME(MONTH, date),
MONTH(Date)
ORDER BY MONTH(Date)