GROUP_CONCAT订购


137

我有一张桌子,像:

+-----------+-------+------------+
| client_id | views | percentage |
+-----------+-------+------------+
|         1 |     6 |         20 |
|         1 |     4 |         55 |
|         1 |     9 |         56 |
|         1 |     2 |         67 |
|         1 |     7 |         80 |
|         1 |     5 |         66 |
|         1 |     3 |         33 |
|         1 |     8 |         34 |
|         1 |     1 |         52 |

我试过了group_concat

SELECT li.client_id, group_concat(li.views) AS views,  
group_concat(li.percentage) FROM li GROUP BY client_id;

+-----------+-------------------+-----------------------------+
| client_id | views             | group_concat(li.percentage) |
+-----------+-------------------+-----------------------------+
|         1 | 6,4,9,2,7,5,3,8,1 | 20,55,56,67,80,66,33,34,52  |
+-----------+-------------------+-----------------------------+

但我想按顺序获取视图,例如:

+-----------+-------------------+----------------------------+
| client_id | views             | percentage                 |
+-----------+-------------------+----------------------------+
|         1 | 1,2,3,4,5,6,7,8,9 | 52,67,33,55,66,20,80,34,56 |
+-----------+-------------------+----------------------------+

2
表中的视图值和百分比值是否存储为逗号分隔的值?
维伦德拉

不,它们不是那样存储的,但是我通过查询进行了存储,即使用group_concat
ronquiq 2011年

Answers:


304

您可以通过以下方式ORDER BYGROUP_CONCAT函数内部使用:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC) AS views, 
group_concat(li.percentage ORDER BY li.percentage ASC) 
FROM li GROUP BY client_id

11
是否应该group_concat(li.percentage ORDER BY li.views ASC)按照原始帖子的要求按与视图匹配的顺序显示百分比?
凯·卡弗

@aleroot,此查询特定于MySQL吗?
Pacerier

是的,GROUP_CONCAT是仅MySQL的函数,但是可以使用代理函数在其他数据库上实现类似的结果...
aleroot

2
如果按与group_concat()相同的表达式对group_concat进行排序,则只需编写即可group_concat(li.views ORDER BY 1)。最简单!
Doin 2015年

1
如果您也使用分隔符: SELECT GROUP_CONCAT(CONCAT(u.RegionName,'-',u.UserName) ORDER BY u.RegionName SEPARATOR '@@')
喜马拉雅山Garg'Mar



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.