0

我有两张桌子leadlead_details. 有一个领域status。如果status=1打开,status=2则关闭status=3且未指定。

我想找到所有打开、关闭和未为每个用户/代理指定的总和。这是我尝试过的,但它给了我错误的数据

select agent_id,
       type,
       status,
       created_date,
       category_id,
       sum(case when status = 2 then val else 0 end) as closed1,
       sum(case when status = 1 then val else 0 end) as opened1, 
       sum(case when status = 3 then val else 0 end) as notspecefied1 
  from ( select l.agent_id,
                l.type,
                ld.category_id,
                l.status,
                l.created_date,
                count(*) as val 
           from crm_leads l,
                crm_leads_details ld 
          where l.id=ld.lead_id AND  
                status in (2, 1, 3) 
          GROUP BY status, agent_id 
        ) t 
 WHERE created_date BETWEEN '2013-8-2' AND '2013-9-2' 
 GROUP BY agent_id
4

1 回答 1

1

您需要将该WHERE created_date子句放在子查询中。

select agent_id,type,status,created_date,category_id,
       sum(case when status = 2 then val else 0 end) as closed1,
       sum(case when status = 1 then val else 0 end) as opened1, 
       sum(case when status = 3 then val else 0 end) as notspecefied1 
from ( select l.agent_id,l.type,ld.category_id,l.status,l.created_date,
       count(*) as val from crm_leads l JOIN crm_leads_details ld 
       ON l.id=ld.lead_id 
       WHERE created_date BETWEEN '2013-8-2' AND '2013-9-2' AND status in (2, 1, 3)
       GROUP BY status, agent_id ) t 
GROUP BY agent_id

请注意,created_date结果中的 只是每个代理期间随机选择的日期。

于 2013-09-02T11:40:05.777 回答