简体   繁体   English

查找重复项并在sql中合并其值

[英]find duplicates and merge their values in sql

I have a database table that contains a list of schools and names: 我有一个数据库表,其中包含学校和姓名的列表:

school    name    point
------------------------
first     dani    good
first     dani    precise
third     John    nice
first     dani    pro
third     John    cute

I want to end up with just one record for each school / name combination and merge the point values like this: 我想以每个学校/名称组合的唯一记录结束,并合并点值,如下所示:

school    name    point
--------------------------------------
first     dani    good and precise and pro
third     John    cute and nice

You can use GROUP_CONCAT like that to get the results : 您可以像这样使用GROUP_CONCAT来获得结果:

SELECT school, name, GROUP_CONCAT(point SEPARATOR ' and ') points
FROM table
GROUP BY school, name

If it's ok and you want to replace your actually table with the results, create the same table with another name tmptable for example. 如果可以,并且您要用结果替换实际的表,则使用另一个名称tmptable创建相同的表。

INSERT INTO tmptable
SELECT school, name, GROUP_CONCAT(point SEPARATOR ' and ') points
FROM table
GROUP BY school, name;

DROP TABLE table;
RENAME TABLE tmptable TO table;

Here you see the result in an sqlfiddle 在这里,您可以在sqlfiddle中看到结果

here is a sample that will works for you 这是一个适合您的样本

and a new one with DISTINCT 还有一个新的DISTINCT

SELECT
  school,
  `name`,
  GROUP_CONCAT( `point` SEPARATOR ' and ')
FROM ( SELECT DISTINCT school,`name`, `point` FROM groupme) AS result
GROUP BY school,`NAME`;

SELECT
  school,
  `name`,
  GROUP_CONCAT( `point` SEPARATOR ' and ')
FROM groupme
GROUP BY school,`name`;

Sample 样品

MariaDB [mysql]> select * from groupme;
+----+--------+------+---------+
| id | school | name | point   |
+----+--------+------+---------+
|  1 | first  | dani | good    |
|  2 | first  | dani | precise |
|  3 | third  | John | nice    |
|  4 | first  | dani | pro     |
|  5 | third  | John | cute    |
+----+--------+------+---------+
5 rows in set (0.01 sec)

MariaDB [mysql]> SELECT school, `name` , GROUP_CONCAT( `point` SEPARATOR ' and ')
    -> FROM groupme
    -> GROUP BY school,`name`;
+--------+------+------------------------------------------+
| school | name | GROUP_CONCAT( `point` SEPARATOR ' and ') |
+--------+------+------------------------------------------+
| first  | dani | good and precise and pro                 |
| third  | John | nice and cute                            |
+--------+------+------------------------------------------+
2 rows in set (0.00 sec)

MariaDB [mysql]>

Using @ebahi's answer: 使用@ebahi的答案:

Change the query into as mentioned by @fuzzytree: 将查询更改为@fuzzytree中提到的内容:

SELECT school, name, GROUP_CONCAT(distinct point SEPARATOR ' and ') points
FROM table
GROUP BY school, name

sqlfiddle to see the result sqlfiddle查看结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM