【问题标题】:How to get distinct values using group_concat() in sql [duplicate]如何在 sql [重复] 中使用 group_concat() 获取不同的值
【发布时间】:2021-08-18 02:35:57
【问题描述】:

我想要以“,”作为分隔符的特定月份、州和城市的所有不同快递代码。我尝试了 group_concat() 但代码重复。

示例表

Month City State Pincode Courier Total_orders
1 City1 State1 110021 DTDC 20000
1 City1 State1 110021 GA 30000
2 City1 State1 110021 DTDC 10000
1 City2 State2 110029 DTDC 25000
1 City2 State2 110029 DTDC 20000
1 City2 State2 110029 DTDC 15000
select distinct Pincode, Month, City, State, 
sum(Total_orders) as Total_orders, 
group_concat(Courier) as CourierType
from table1
group by Pincode, Month

输出:

Month City State Pincode CourierType Total_orders
1 City1 State1 110021 DTDC,GA 50000
2 City1 State1 110021 DTDC 10000
1 City2 State2 110029 DTDC,DTDC,DTDC 60000

但是有什么方法可以让我只获得不同的代码而不是“DTDC、DTDC、DTDC”?对于一个庞大的数据集,这个重复快递类型的列变得很乱。

期望的输出:

Month City State Pincode CourierType Total_orders
1 City1 State1 110021 DTDC,GA 50000
2 City1 State1 110021 DTDC 10000
1 City2 State2 110029 DTDC 60000

【问题讨论】:

    标签: mysql sql group-concat


    【解决方案1】:

    我认为您只希望 group_concat(distinct) 具有正确的 group by 列:

    select Pincode, Month, City, State, 
           sum(Total_orders) as Total_orders, 
           group_concat(distinct Courier) as CourierType
    from table1
    group by Pincode, Month, City, State
    

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2012-02-15
      相关资源
      最近更新 更多