如何检查某些变量是否同时连续3年排名前5位?

时间:2019-01-22 19:38:48

标签: mysql sql ranking

希望你们一切都好。

我正在为一家使用SQL(MySql)的公司进行测试,但有一个问题我真的不知道该如何回答。问题是“在2008年,2009年和2010年,是否有任何制造商同时在销售量中排名前5位?”

该表具有SALEID,MANUFACTURER,QUANTITY,TOTALVALUE和DATE相当直观。

查询应返回一个包含5行的表,其中包含制造商和已售出的总数量。但是,应该只出现在过去3年中排名前5位的销售合作伙伴中的制造商,如果没有制造商,则应显示为“ NULL”或na或任何表示没有该制造商的信息。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:-1)

我只加入3个有限制的子查询,按每个制造商的总销售额排序。

无论如何对于MySql5.x。
(缺少窗口功能)

SELECT 
  COALESCE(q10.Manufacturer, 'NA') as  Manufacturer,
  (q08.TotalQuantity + q09.TotalQuantity + q10.TotalQuantity) as TotalQuantity
FROM
(
    SELECT Manufacturer, SUM(Quantity) AS TotalQuantity, SUM(TotalValue) AS TotalValue
    FROM Sales
    WHERE `Date` BETWEEN '2008-01-01' AND '2008-12-31'
    GROUP BY Manufacturer
    ORDER BY TotalQuantity DESC, TotalValue DESC
    LIMIT 5
) q08
LEFT JOIN 
(
    SELECT Manufacturer, SUM(Quantity) AS TotalQuantity, SUM(TotalValue) AS TotalValue
    FROM Sales
    WHERE `Date` BETWEEN '2009-01-01' AND '2009-12-31'
    GROUP BY Manufacturer
    ORDER BY TotalQuantity DESC, TotalValue DESC
    LIMIT 5
) q09 ON q09.Manufacturer = q08.Manufacturer
LEFT JOIN
(
    SELECT Manufacturer, SUM(Quantity) AS TotalQuantity, SUM(TotalValue) AS TotalValue
    FROM Sales
    WHERE `Date` BETWEEN '2010-01-01' AND '2010-12-31'
    GROUP BY Manufacturer
    ORDER BY TotalQuantity DESC, TotalValue DESC
    LIMIT 5
) q10 ON q10.Manufacturer = q09.Manufacturer
ORDER BY TotalQuantity DESC

上个月测试 here