单个记录,逗号分隔值

时间:2014-05-30 12:18:00

标签: mysql sql

我正在使用像

这样的SQL查询
SELECT fun_systemuser(UserID) as ConsultantName,
       fun_store(UserID) as StoreName,
       count(UserID) as No_of_PhoneModel,
       PhoneModelID,
       (select LeegraRegion 
          from store 
         where ID=claim.StoreID) as Region,
       fun_network(UserID) as ChannelName,
       fun_group(claim.StoreID) as GroupName,
       fun_campaigns(UserID) as CampaignName  
  FROM `claim` 
 where UserID IN (SELECT id 
                    FROM `systemuser` 
                   WHERE `RoleID`=1 
                     and `Topconsultant`=1) 
   and StatusID=5 
 group by UserID ,PhoneModelID

我的查询结果如下:

enter image description here

对于具有不同电话型号ID且没有的单个顾问,有4条记录。手机型号的销售情况。

我想为每个顾问名单单独记录,并且应该显示手机型号和带逗号分隔值的手机型号。

实施例。单个记录应显示如下

Thomson 4U-Sunnypark 3,2,3,1  1,3,6,9 Pretoria Vodacom Sachar Mobile vodacom Campaigns

有人知道我应该在查询中使用什么,这样我就能得到我想要的结果。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您必须使用GROUP_CONCAT。例如:

  SELECT ConsultantName,
         StoreName,
         GROUP_CONCAT(DISTINCT No_of_Phonemodel SEPARATOR ',') ,
         GROUP_CONCAT(DISTINCT PhoneModelID SEPARATOR ',') ,
         Region
    FROM (
           SELECT fun_systemuser(UserID) as ConsultantName,
                  fun_store(UserID) as StoreName,
                  count(UserID) as No_of_PhoneModel,
                  PhoneModelID,
                  (select LeegraRegion 
                     from store 
                    where ID=claim.StoreID) as Region,
                  fun_network(UserID) as ChannelName,
                  fun_group(claim.StoreID) as GroupName,
                  fun_campaigns(UserID) as CampaignName  
             FROM `claim` 
            where UserID IN (SELECT id 
                               FROM `systemuser` 
                              WHERE `RoleID`=1 
                                and `Topconsultant`=1) 
              and StatusID=5 
            group by UserID ,PhoneModelID
         ) as S
GROUP BY ConsultantName,
         StoreName,
         Region