MySql:连接存在重复项的列

MySql:连接存在重复项的列,mysql,mysql-workbench,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.Divi

我有以下疑问:

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
问:如何修改我的查询,使其仅在存在重复产品的情况下连接产品和部门,并显示重复产品,如上面的示例所示?

这应该有效。使用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)
 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)
没有提供关于整个数据集的足够数据,因此我只处理了连接部分

pd是表的名称。内容包括:

mysql> select * from pd;
+----------+-----------+
| product  | division  |
+----------+-----------+
| Product1 | Division1 |
| Product1 | Division2 |
| Product2 | Division3 |
| Product3 | Division4 |
+----------+-----------+
4 rows in set (0.00 sec)
在@DaveRandom的帮助下,查询的另一个版本如下:

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)
 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)

可能会在group by后面添加having子句,因为having count*>1注意group by需要在Product上我也需要显示重复项,只是为了仅在duplicatestry上连接,因为当count*>1时,ConcatProduct,'',否则产品结尾为'Product',不起作用…@alex:它起作用,您可能需要使用它。