计算sql查询的顺序和数量

时间:2017-03-25 18:56:14

标签: mysql

下午好,Stack Overflow社区!我对sql和编写查询都很陌生,所以如果有人可以仔细检查我的工作,并且可能会传递任何有用的提示,以便我可以更好地编写代码?我已经按照查询和我的代码的目的粘贴了 - 感谢您的帮助和反馈!

基本上,该查询应创建一份生活在欧洲的客户的报告,这些客户最近下订单总额超过5,000美元。订单总额必须反映客户订购的产品数量,也应该有折扣和订单总数。

再次感谢您的帮助!

select c.CustomerID, c.Country, sum (od.Discount * od.UnitPrice)'Total'
from Customers c
inner join Orders o
on c.CustomerID = o.CustomerID
inner join OrderDetails od
on o.OrderID = od.OrderID
where c.Country in ('germany', 'UK', 'sweden', 'france', 'spain', 'switzerland','austria', 'italy', 'belgium', 'norway', 'denmark', 'finland', 'poland') 
group by c.Country, c.CustomerID
having sum ('Total' * od.Quantity) <= 5000
order by total desc

1 个答案:

答案 0 :(得分:0)

看起来不错,但有几点: 1)您的Total可能是错的 2)您必须反转比较运算符:

select c.CustomerID, c.Country, sum (od.Discount * od.UnitPrice * od.Quantity) 'Total'
from Customers c
inner join Orders o
on c.CustomerID = o.CustomerID
inner join OrderDetails od
on o.OrderID = od.OrderID
where c.Country in ('germany', 'UK', 'sweden', 'france', 'spain', 
  'switzerland','austria', 'italy', 'belgium', 'norway', 'denmark', 
  'finland', 'poland') 
and o.OrderDate >= '2017-03-01' -- for example
group by c.Country, c.CustomerID
having sum ( od.Discount * od.UnitPrice * od.Quantity) >= 5000
order by total desc