我试图在SQL中编写一个查询,计算当前年度每月订单总额(美元金额)。
我的表是这样设置的:
OrderID OrderTotal OrderDate
5598745 85.70 2016-07-29
5598744 184.75 2016-07-25
5598743 847.50 2016-06-20
5598742 50.00 2016-06-05
所以我的查询应该显示如下:
June $897.50
July $270.45
etc...
我没有成功地使用它:
SELECT
month(OrderDate) AS month_name,
SUM(OrderTotal) AS sum_of_month,
AVG(SUM(OrderTotal)) OVER () AS avg_sum
FROM
[db].[dbo].[orders]
WHERE
YEAR(OrderDate) = YEAR(GetDate())
答案 0 :(得分:1)
月份总和你应该使用分组
SELECT month(OrderDate) AS month_name,
SUM(OrderTotal) AS sum_of_month
AVG(OrderTotal) AS AVG_of_month
FROM [db].[dbo].[orders]
WHERE YEAR(OrderDate) = YEAR(GetDate())
GROUP BY month(OrderDate);
答案 1 :(得分:1)
使用DateName()获取月份名称
Declare @Table table (OrderTotal money,OrderDate Date)
Insert into @Table values
(85.70,'2016-07-29'),
(184.75,'2016-07-25'),
(847.50,'2016-06-20'),
(50.00,'2016-06-05')
Select MonthName=DateName(MM,OrderDate)
,Total=sum(OrderTotal)
From @Table
Where Year(OrderDate) = Year(GetDate())
Group By Month(OrderDate),DateName(MM,OrderDate)
Order By Month(OrderDate)
返回
MonthName Total
June 897.50
July 270.45
答案 2 :(得分:0)
试试这可能有效
SELECT
month(OrderDate) AS month_name,
SUM(OrderTotal) AS sum_of_month,
AVG(SUM(OrderTotal)) OVER () AS avg_sum
FROM
[db].[dbo].[orders]
WHERE
YEAR(OrderDate) = YEAR(GetDate())
order by month(OrderDate)
答案 3 :(得分:0)
这是一个简单的查询,用于计算每月的总和。
select datename(month, dateadd(month, month(OrderDate), 0) - 1) as month_name,
sum(OrderTotal) as sum_of_month
from Orders
where year(OrderDate) = year(getdate())
group by month(OrderDate)
order by month(OrderDate)
您似乎希望获得所有总和的平均值。我不认为将它呈现在此表中是个好主意。每行将显示相同的数字。相反,我建议单独的查询:
select avg(t.month_sum) from
(select sum(OrderTotal) as month_sum from Orders
where year(OrderDate) = year(getdate())
group by month(OrderDate)
) as t