简体   繁体   中英

Query with sum case group by

I am facing problem with following query:

 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

The problem is that this query is returning results for customer with same id though I used group by . For example, in the month of September, if same customer visits 5 times it is returning count as 5 instead of 1 though I used group by .

Update Ans -

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

It is really unclear what you want... Yes, distinct customers for a given time period, but then you are taking the month of the date visited -1 and looking for that equal to 8. Being that current month is 9 (September), Are you just looking for those based on activity the month prior to whatever the current is? So, for example, if Sept, 2015, you want totals for Aug, 2015. In Jan, 2016, you would want Dec, 2015? If that is the case, you can use the current date to subtract 1 month and get that as basis of the query. Then you can have your additional specific client (65 in this case).

My (subselect sqlvars) pre-creates variables applied for the query. It computes one month ago by subtracting 1 month from whatever the current date it. Then uses that as basis of the month representing whatever was the prior month, and similarly for that respective year.

Since this will in essence create a single row return, there is no Cartesian result and you can just run with your original other tables for final counts.

select
      count( distinct s.customer_id ) as UniqueCustomers
   from
      ( select @oneMonthAgo := DATE_ADD(CURRENT_DATE, INTERVAL -1 MONTH),
               @finalMonth := MONTH( @oneMonthAgo ),
               @finalYear := YEAR( @oneMonthAgo ) sqlvars,
      customer_visit_status_tbl s
         JOIN customer_details_tbl c
            on s.customer_id = c.customer_id
           AND c.client_id = 65
   where
      s.new_reg_yn='n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM