繁体   English   中英

现实世界总销售额SQL查询

[英]Real world total sales SQL query

我对SQL相当陌生,很难解决问题。

'对于按单位销量最高的五种单独产品中的每一种都至少售出一个单位的销售人员,所有产品的总销售额是多少? 确保查询以降序返回总销售美元。 仅考虑在@target_date参数之前的六个月内完成的销售。”

数据库中存在3个表。
SalesPerson( SalesPersonID ,SalesYTD)
SalesOrderHeader( SalesOrderID ,OrderDate,ShipDate)
SalesOrderDetail( SalesOrderIDSalesOrderDetailID ,OrderQty,ProductID,UnitPrice)

这是我到目前为止的位置。 我需要将我所拥有的内容汇编成一个陈述并进行必要的修改。 请帮忙!

要按单元获得前5名最高的销售额,应使用以下SYNTAX:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM