我有下表:
category product sale
C1 P1 10
C2 P2 12
C3 P1 14
C1 P2 15
C1 P1 16
C2 P2 10
C2 P3 22
C3 P1 01
C3 P2 27
C3 P3 02
我想按类别分组并获得销售总额,以及每个类别中的顶级产品。 (顶级产品实际上是产品中出现的最多产品,而不是通过销售)
预期输出:
category Top product Total sales
C1 P1 38
C2 P2 44
C3 P1 44
我编写了以下MySQL查询,但出现错误(产品的列名称无效):
SELECT SUM(product) AS pro FROM
(SELECT category, count(sale)
FROM `table`
GROUP BY `table`.`category`
) as t2
ORDER BY pro DESC LIMIT 1
我正在努力编写正确的MySQL查询,有人可以指出问题吗?
答案 0 :(得分:1)
要获得每个类别的销售总额以及顶级产品,您可以使用相关/相关子查询,如下所示:
select t.category,
sum(t.sale) sales,
(select product
from demo
where category = t.category
group by product
order by count(*) desc
limit 1) top_product
from demo t
group by t.category
答案 1 :(得分:1)
您可以使用Correlated Subquery来获得某个类别中销量最高(销量最高)的产品。请尝试以下操作:
SELECT
t.category,
SUM(t.sale) AS total_sales,
(SELECT t2.product
FROM `table` AS t2
WHERE t2.category = t.category
ORDER BY t2.sale DESC LIMIT 1) AS top_product
FROM
`table` AS t
GROUP BY t.category
答案 2 :(得分:1)
仅MySQL解决方案,因此当您需要代码中的数据库可移植性时不要使用此解决方案。
结合使用GROUP_CONCAT
和嵌套的SUBSTRING_INDEX
函数来获取第一个元素/项目,也可以用来获取额外的列,以保留正确的分组信息。
注意:SET SESSION group_concat_max_len = @@max_allowed_packet;
的使用非常重要,否则GROUP_CONCAT
仅显示1024字节。
查询
SET SESSION group_concat_max_len = @@max_allowed_packet;
SELECT
Table1.category
, SUM(Table1.sale) sum_per_category
, SUBSTRING_INDEX(
SUBSTRING_INDEX(
GROUP_CONCAT(product ORDER BY sale DESC)
, ','
, 1
)
, ','
, -1
) AS most_sold_product_in_category
FROM
Table1
GROUP BY
Table1.category
结果
| category | sum_per_category | most_sold_product_in_category |
|----------|------------------|-------------------------------|
| C1 | 26 | P3 |
| C2 | 12 | P2 |
| C3 | 14 | P1 |
| C4 | 15 | P2 |
答案 3 :(得分:0)
这可能有效:
SELECT t2.category, t2.sales,(select product
from `table`
where sale=(select max(b.sale)
from `table` b
where b.category=t2.category) limit 1)
FROM
(SELECT category, sum(sale) as sales
FROM `table`
GROUP BY `table`.`category`
) as t2
答案 4 :(得分:0)
Select q.*,SUM(sale) from
(SELECT *
FROM `categories` order by sale desc limit 50
) as q group by q.category