MySql中的Group_concat

时间:2014-05-06 06:08:43

标签: mysql group-concat

我有一个包含一些记录的示例表。我显示表结构和预期输出。请帮我这样做。现在我使用Group_Concat但它在ids字段中显示1,1和2,2和3,3。

ID  PRODUCT     QUANTITY
1   COMPUTER    100
2   MOUSE       120
3   KEYBOARD    10
4   MOUSE       150
5   KEYBOARD    300
6   COMPUTER    20
7   KEYBOARD    1

预期输出

ID  PRODUCT QUANTITY    IDS
1   COMPUTER    120     1,6
2   MOUSE       270     2,4
3   KEYBOARD    311     3,5,7

3 个答案:

答案 0 :(得分:1)

试试这样:

select min(id) ID, product, sum(quantity), group_concat(id) IDS
from table1
group by product
order by min(id);

答案 1 :(得分:0)

使用sum获取总数量,group by product然后order by id

示例

select
  product, sum( quantity ) as quantity
  , group_concat( id ) as ids
from products
group by product
order by id
;

答案 2 :(得分:0)

ORDER BY ID(外部)将显示产品的第一个ID,
group_concat中的DISTINCT强制所有id都是不同的,ORDER BY使它们按顺序排列
试试这个:

SELECT
    ID, PRODUCT, SUM(QUANTITY) QUANTITY, GROUP_CONCAT(DISTINCT ID ORDER BY ID) IDS
FROM
    <table>
GROUP BY PRODUCT
ORDER BY ID
;