我的sql查询根据多个条件求和列值

时间:2016-07-21 12:47:24

标签: mysql

查询表的结果

 SELECT cc.Contact_ID
      , SUM(HeadCount)
      , c.ClientID
      , c.Client_Name 
      , cc.Contact_Name
      , cc.Role
      , cs.Communication
      , cs.ResponseTime
      , cs.LeadershipStyle
      , cs.Trust
      , cs.Sentiment
   FROM client c 
   LEFT 
   JOIN client_contact cc 
     ON c.ClientID = cc.Client_ID 
   JOIN process p 
     ON c.ClientID = p.ClientID 
    AND cc.Contact_Process = p.ProcessID
   JOIN verticals v 
     ON v.VerticalID = cc.Contact_Vertical
   LEFT 
   JOIN client_sentimental_indicator cs 
     ON cs.ClientContactID = cc.Contact_ID
  WHERE c.STATUS = 1 
    AND p.ProcessStatus = 0
    AND cc.status = 0   
  GROUP 
     BY c.ClientID
      , cc.Contact_ID
  ORDER 
     BY c.client_Name

这是表格结果

ID  Sum(headcount) CID     CName        contname
339   6            340      xxx         Inc Andy Stetson        
340   3            340      xxx         Danielle du Toit        
351   3            322      yyy         Ron Mahulkar        
350   3            322      zzz         Nicholas Ho     
349   3             322     zzz         Will Power      
271   74            102     vvv         Carie Hinton        
338   31            102     vvv         Linda Dunn      
283   9             102     vvv         Waseem Khan 

我需要结果如下

ID  Sum(headcount) exactSum CID    CName        contname
339   6            9        340     xxx         Inc Andy Stetson        
340   3                     340     xxx         Danielle du Toit        
351   3            3        322     yyy         Ron Mahulkar        
350   3                     322     zzz         Nicholas Ho     
349   3                     322     zzz         Will Power      
271   74           114      102     vvv         Carie Hinton        
338   31                    102     vvv         Linda Dunn      
283   9                     102     vvv         Waseem Khan 

我有CID重复,需要重复显示,总和应该根据CID

完成

请帮帮忙

1 个答案:

答案 0 :(得分:0)

SELECT cid
     , MIN(id)
     , SUM(subtotal
  FROM 
     ( SELECT cc.Contact_ID
            , SUM(HeadCount) subtotal
            , c.ClientID
            , c.Client_Name 
            , cc.Contact_Name
            , cc.Role
            , cs.Communication
            , cs.ResponseTime
            , cs.LeadershipStyle
            , cs.Trust
            , cs.Sentiment
         FROM client c 
         LEFT 
         JOIN client_contact cc 
           ON c.ClientID = cc.Client_ID 
         JOIN process p 
           ON c.ClientID = p.ClientID 
          AND cc.Contact_Process = p.ProcessID
         JOIN verticals v 
           ON v.VerticalID = cc.Contact_Vertical
         LEFT 
         JOIN client_sentimental_indicator cs 
           ON cs.ClientContactID = cc.Contact_ID
        WHERE c.STATUS = 1 
          AND p.ProcessStatus = 0
          AND cc.status = 0     
        GROUP 
           BY c.ClientID
            , cc.Contact_ID
      ) a
  GROUP
     BY cid;