用和案例组查询

时间:2015-09-22 06:11:12

标签: mysql sql

我遇到以下问题的问题:

 SELECT sum(CASE WHEN status.new_reg_yn='n'
                  AND month(status.visit_date)-1 = 8
                  AND year(status.visit_date) = 2015 THEN 1 ELSE 0 END)
 FROM customer_visit_status_tbl status,
      customer_details_tbl cust
 WHERE status.customer_id = cust.customer_id
   AND cust.client_id=65
 GROUP BY status.customer_id

问题是,虽然我使用了group by,但此查询会返回具有相同ID的客户的结果。例如,在9月份,如果同一客户访问5次,则返回计数为5而不是1,尽管我使用了group by

1 个答案:

答案 0 :(得分:0)

更新答案 -

Select count(*) 
  from 
     ( SELECT distinct status.customer_id 
                  FROM customer_visit_status_tbl status
                     , customer_details_tbl cust 
                 WHERE status.customer_id = cust.customer_id 
                   AND cust.client_id = 65 
                   and status.new_reg_yn = 'n' 
                   AND month(status.visit_date)-1 = 8 
                   AND year(status.visit_date) = 2015
     ) customer_visited