MySql:Concatenate列,其中有重复项

时间:2014-11-24 10:44:38

标签: mysql mysql-workbench

我有以下查询:

SELECT Number, Concat(Product,' ',Division) as 'Product', 
count(*) as 'COUNT', SUM(tta) as 'TTA', ROUND(SUM(tta) / count(*),2) as 'AVG' 
FROM cdrdata cdr 
LEFT JOIN products p ON p.Number = cdr.calling 
LEFT JOIN divisions d ON d.id = p.DivisionID 
WHERE CustomerID = 32 AND p.Status = 1 
Group by calling
ORDER BY Product;

结果:
由此:

Product1 DIvision1
Product1 Division2
Product2 Division3
Product3 Division4

对此:

Product1 Division1
Product1 Division2
Product2
Product3

问:如何修改我的查询,以便仅在存在重复Product的情况下连接DivisionProducts并显示重复项,像上面的例子一样?

1 个答案:

答案 0 :(得分:0)

这应该有效。使用MySQL的group_concat()

查询如下:

mysql> SELECT  group_concat(product,' ',division SEPARATOR '\n') as products FROM pd GROUP BY product HAVING count(product) > 1;
+---------------------------------------+
| products                              |
+---------------------------------------+
| Product1 Division1
Product1 Division2 |
+---------------------------------------+
1 row in set (0.00 sec)

没有提供关于整个数据集的足够数据,所以我只使用了连接部分。

pd是表的名称。内容如下:

mysql> select * from pd;
+----------+-----------+
| product  | division  |
+----------+-----------+
| Product1 | Division1 |
| Product1 | Division2 |
| Product2 | Division3 |
| Product3 | Division4 |
+----------+-----------+
4 rows in set (0.00 sec)

在@DaveRandom的帮助下,查询的另一个版本如下:

 SELECT DISTINCT a.* FROM pd a INNER JOIN pd b ON a.product = b.product AND a.division <> b.division;

mysql> SELECT DISTINCT a.* FROM pd a INNER JOIN pd b ON a.product = b.product AND a.division <> b.division;
+----------+-----------+
| product  | division  |
+----------+-----------+
| Product1 | Division2 |
| Product1 | Division1 |
+----------+-----------+
2 rows in set (0.00 sec)