我有问题。我在MySQL中有以下表格:
+---------+ +-----------+ +---------+
| USER | | USER_LANG | | LANG |
| id_user | | id_user | | id_lang |
| name | | id_lang | | name |
| | | years | | |
+---------+ +-----------+ +---------+
我有以下信息:
+--------------------------------+
| ID_USER | ID_LANG | YEARS |
| 1 | 5 | 1 |
| 1 | 6 | 2 |
| 2 | 5 | 9 |
| 2 | 6 | 3 |
| 3 | 5 | 7 |
+--------------------------------+
我需要实现的是对所有使用完全相同语言组的用户进行分组并总结年份。例如,我需要得到的是:
+----------------------+
| LANGS | SUM_YEARS |
| 5;6 | 15 |
| 5 | 7 |
+----------------------+
这很奇怪,但我需要这个。我试过GROUP_CONCAT但没有用。
希望他们可以帮助我。
提前致谢。
答案 0 :(得分:3)
这是一个不寻常的请求,但它应该与子查询中的GROUP_CONCAT()
一起使用:
/* Outer query groups the concatentated langs and sums years */
SELECT
LANGS,
SUM(YEARS) AS TOTAL_YEARS,
/* Edit: bonus list of users speaking the languages */
GROUP_CONCAT(ID_USER) AS USER_GROUP
FROM (
/* Subquery gets group concat of languages & sum per user */
SELECT
ID_USER,
GROUP_CONCAT(ID_LANG) AS LANGS,
SUM(YEARS) AS YEARS
FROM USER_LANG
GROUP BY ID_USER
) USER_SUB
GROUP BY LANGS