gpt4 book ai didi

mysql - 根据获奖产品添加行 "Type"

转载 作者:行者123 更新时间:2023-11-29 11:21:04 25 4
gpt4 key购买 nike

我有一个名为“CustomerSales”的表。客户经常购买多种产品。我想创建一个查询,查看所有客户并选择最畅销的产品,插入一行包含最畅销产品的名称。

示例。

Customer-Product-Sales
Joe-1a $200
Joe-2a $10
Joe-3a $100
Alice-2a $400
Alice-3a $300
Alice-1a $50
Dawn-3a $1000
Dawn -2a $50
Dawn -1a $10

例如,鉴于此数据,我喜欢在查询中插入一行,表示 Joe 的“顶级产品”是 1a,Alice 是 2a,Dawn 是 3a。

最佳答案

如果您的数据不是很大,那么 substring_index()/group_concat() 技巧非常有效:

select customer,
substring_index(group_concat(product order by sales desc), ',', 1) as TopProduct
from t
group by customer;

这是另一种没有group by的方法:

select t.*
from t
where t.sales = (select max(t2.sales) from t t2 where t2.customer = t.customer);

此方法的问题是并列第一的产品将导致输出中出现多行。实际上,您可以通过选择其中任意一个来解决这个问题:

select t.*
from t
where t.sales = (select t2.sales
from t t2
where t2.customer = t.customer
order by t2.sales desc
limit 1
);

关于mysql - 根据获奖产品添加行 "Type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com