作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个名为“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/
我是一名优秀的程序员,十分优秀!