每天列出每个类别中最畅销的商品,包括总销售量和收入

时间:2018-07-08 03:30:38

标签: mysql sql

我有一个如下的购买表

customerID orderID  item   category     purDate   sold price
    1        001    book   stationary   1/1/2018    1   5
    2        002    ball    toys        1/1/2018    2   2
    3        003    shirt   cloth       1/1/2018    1   10
    1        004    pen    stationary   1/1/2018    5   3
    4        005    shirt   cloth       1/1/2018    2   10
    5        006    card    stationary  1/2/2018    15  2
    6        007    tshirt  cloth       1/2/2018    3   7
    2        008    book    stationary  1/3/2018    6   5
    3        009    car      toys       1/3/2018    2   4
    1        010    book    stationary  1/3/2018    4   5
    4        011    ball     toys       1/4/2018    2   2
    6        012    pen     stationary  1/4/2018    2   3
    7        013    notebk  stationary  1/4/2018    2   3

并且我想使用MySQL查询每天和类别中最畅销的商品,以便查询结果看起来像

purDate     category    item   total revenue
1/1/2018    stationary  pen       5     15
1/1/2018     toys       ball      2      4
1/1/2018     cloth      shirt     3     30
1/2/2018    stationary  card     15     30
1/2/2018     cloth      tshirt    3     21
1/3/2018    stationary  book     10     50
1/3/2018     toys       car       2      8
1/4/2018     toys       ball      2      4
1/4/2018    stationary  pen       2      6
1/4/2018    stationary  notebk    2      6

我已经检查了关于stackoverflow的其他相关主题,但是找不到我想要的东西。我正在尝试将窗口函数与聚合函数一起使用,但是一直失败。

SELECT purDate, category, item, total, revenue 
 FROM (SELECT purDate, category, item, SUM(sold) AS total, sold * price AS revenue, 
   RANK() OVER(PARTITION BY purDate, category ORDER BY SUM(sold) DESC) AS rank 
 GROUP BY 1,2,3) q
 WHERE q.rank = 1

谢谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您在内部查询中错过了一个FROM。而且您也错过了按price分组并建立revenuesum(sold) * price的机会。除此之外,您绝对在正确的道路上。

SELECT purdate,
       category,
       item,
       total,
       revenue
       FROM (SELECT purdate,
                    category,
                    item,
                    sum(sold) total,
                    sum(sold) * price revenue,
                    rank() OVER (PARTITION BY purdate
                                 ORDER BY sum(sold) DESC) r
                    FROM purchase
                    GROUP BY purdate,
                             category,
                             item,
                             price) x
       WHERE r = 1
       ORDER BY purdate;

db<>fiddle

答案 1 :(得分:1)

不要害怕将您要完成的工作分解为多个步骤,而不是一个庞大的查询。

Create table bleach select 
pur_date, max(sold) as max_sold, 
'' as total_rev
from your_table group by 
pur_date;

Alter table bleach add 
index(pur_date);

Alter table bleach add index 
(max_sold);

Select a.* from your_table a, 
bleach b where 
a.pur_date=b.pur_date and 
a.max_sold=b.max_sold;

Update bleach set 
total_rev=sold*price

Drop table bleach;