我对SQL很新,并且很难解决问题。
'销售人员的所有产品的总销售额是多少,这些销售人员按销售额最高的五种单独产品中的每一种销售至少一个单位?确保查询以降序返回总销售额。仅考虑在@target_date参数之前的六个完整月份内进行的销售。'
DB中存在3个表
SalesPerson( SalesPersonID ,SalesYTD)
SalesOrderHeader( SalesOrderID ,OrderDate,ShipDate)
SalesOrderDetail( SalesOrderID , SalesOrderDetailID ,OrderQty,ProductID,UnitPrice)
这是我到目前为止的地方。我需要将我所拥有的内容编译成一个语句并进行必要的修订。请帮忙!
要按单位捕获前五名最高销售额,以下语法应该有效:
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’;
答案 0 :(得分:0)
对于销量前五名,我宁愿提出略微简化的
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