我对 SQL 相当陌生,在解决问题时遇到困难。
“销售人员在销量最高的五种产品中每一种至少销售一种,其所有产品的总销售额是多少?”确保查询按降序返回总销售额。仅考虑 @target_date 参数之前完整六个月内发生的销售情况。”
数据库中存在 3 个表。
销售人员(SalesPersonID,SalesYTD)
SalesOrderHeader (SalesOrderID,OrderDate,ShipDate)
SalesOrderDetail (SalesOrderID,SalesOrderDetailID,OrderQty,ProductID,UnitPrice)
这就是我目前所处的位置。我需要将我所掌握的内容汇编成一份声明并进行必要的修改。请帮忙!
要获取按单位计算的前 5 名最高销售额,应使用以下语法:
SELECT
ProductID,
SUM(Orderqty*Unitprice)
FROM SalesOrderDetail
GROUP BY ProductID
WHERE Orderqty >=1
AND COUNT(productID) =5
ORDER BY SUM(Orderqty*Unitprice) DESC
LIMIT 5;
对于 target_date 参数,我认为它会是这样的?
SELECT
SalespersonID AS ‘Sales Representative’,
SalesYTD AS ‘Total Sales’, target_date
FROM Salesperson
WHERE target_date BETWEEN ‘01-DEC-13’ AND ’01-May-14’;
最佳答案
对于销售额最高的前五名,我宁愿建议稍微简化的
select productid, sum(orderqty * unitprice) as sales
from salesorderdetail
group by productid
order by sales desc
limit 5
在@target_date
之前的六个月,类似
where orderdate between date_sub(@target_date, interval 6 months) and @target_date
<小时/>
假设有一个 FK SalesOrderDetail(SalesPersonID)
,您可以将表和前五名销售额连接为
select p.*
from salesperson p
join salesorderheader h on h.salespersionid = p.salespersionid
join salesorderdetail d on d.salesorderid = h.salesorderid
join (select productid, sum(orderqty * unitprice) as sales
from salesorderdetail
group by productid
order by sales desc
limit 5) t5 on t5.productid = d.productid
where h.orderdate between date_sub(@target_date, interval 6 months) and @target_date
order by p.salesytd desc
关于mysql - 真实世界总销售额 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336515/