Mysql 如何使用特定规则选择最多3列中的前3个值?
因此,我想为每位客户找出每个销售月销售额前三名的卖家 原始表格:Mysql 如何使用特定规则选择最多3列中的前3个值?,mysql,sql,datetime,pivot,greatest-n-per-group,Mysql,Sql,Datetime,Pivot,Greatest N Per Group,因此,我想为每位客户找出每个销售月销售额前三名的卖家 原始表格: create table q2(Sales_Date date, Customer_ID varchar(256), Item varchar(256), Amount float); INSERT INTO q2 VALUES ('2018/8/1' ,'AAA' , 'Apple' , 5600),
create table q2(Sales_Date date, Customer_ID varchar(256), Item varchar(256), Amount float);
INSERT INTO q2
VALUES
('2018/8/1' ,'AAA' , 'Apple' , 5600),
('2018/8/8' ,'AAA' , 'Nike' , 500),
('2018/8/9' ,'AAA' , 'Pear' , 600),
('2018/8/10' ,'AAA' , 'Kindle', 900),
('2018/8/1' ,'BBB' , 'Cola', 20),
('2018/9/12' ,'BBB' , 'LEGO' , 240),
('2018/9/13' ,'CCC' , 'Apple' , 2500),
('2018/9/14' ,'CCC' , 'Kindle' , 5000),
('2018/7/4' ,'CCC' , 'Nike' , 1000),
('2018/9/7' ,'CCC' , 'Pear' , 300),
('2018/9/7' ,'CCC' , 'LEGO' , 50);
预期产出
我尝试过不同的方法,但都不管用。我怎样才能做到这一点
到目前为止,我只能用代码检索到畅销书,但这还不够
SELECT
m.Sales_month,
m.Customer_ID,
m.Item
FROM(
SELECT
Month(Sales_Date) as Sales_month,
Customer_ID,
Amount,
Item,
DENSE_RANK() OVER (PARTITION BY Month(Sales_Date), Customer_ID ORDER BY Amount Desc) AS 'rank'
FROM q2
) as m
WHERE m.rank = 1;
非常感谢 我知道您希望在列中列出每个客户和每个月的前三名销售额 每个客户和每个月的排名记录是一个良好的开端。然后,我们可以对每组前三条记录进行筛选,并使用条件聚合进行透视:
select sales_month, customer_id,
max(case when rn = 1 then item end) as item_1,
max(case when rn = 2 then item end) as item_2,
max(case when rn = 3 then item end) as item_3
from (
select q.*,
date_format(sales_date, '%Y-%m-01') as sales_month,
row_number() over (partition by customer_id, date_format(sales_date, '%Y-%m-01') order by amount desc) as rn
from q2
) q
where rn <= 3
group by sales_month, customer_id
请注意,这包括分组中的销售年度,而不是仅使用月份的原始代码。如果您的数据分布超过一年,这很方便。现在删除的@GMB答案在我看来是正确的,请使用:m.rank非常感谢,这正是我需要的。但是为什么在第一个select语句中使用max作为聚合函数呢?如果我改变不同的聚合函数,比如MIN,结果会不同吗?