【问题标题】:MySql: Concatenate column where there are duplicatesMySql:连接有重复的列
【发布时间】:2014-11-24 10:44:38
【问题描述】:

我有以下疑问:

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

问:如何修改我的查询,以便仅在有重复的Products 的地方连接ProductDivision 并显示重复的内容,如上例所示? p>

【问题讨论】:

  • 可能会在group by 之后添加一个having 子句作为having count(*) > 1 请注意group by 需要在product
  • 我还需要显示重复项,只是为了仅在重复项上连接
  • 试试case when count(*) > 1 then Concat(Product,' ',Division) else Product end as 'Product'
  • 那行不通...
  • @alex:它确实有效,您可能需要使用a derived table

标签: mysql mysql-workbench


【解决方案1】:

这应该可行。使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2017-08-22
    • 2020-09-22
    • 2011-05-30
    • 2014-02-02
    • 2011-12-22
    相关资源
    最近更新 更多