[英]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
.问题是,尽管我使用了
group by
但此查询正在为具有相同 ID 的客户返回结果。 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
.例如,在 9 月份,如果同一客户访问 5 次,则返回计数为 5 而不是 1,尽管我使用了
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?真的不清楚你想要什么......是的,在给定的时间段内有不同的客户,但是你正在取访问日期的月份 -1 并寻找等于 8 的月份。因为当月是 9(九月) , 你只是在寻找那些基于前一个月活动的那些当前是什么? So, for example, if Sept, 2015, you want totals for Aug, 2015. In Jan, 2016, you would want Dec, 2015?
因此,例如,如果 2015 年 9 月,您想要 2015 年 8 月的总数。在 2016 年 1 月,您想要 2015 年 12 月? If that is the case, you can use the current date to subtract 1 month and get that as basis of the query.
如果是这种情况,您可以使用当前日期减去 1 个月并将其作为查询的基础。 Then you can have your additional specific client (65 in this case).
然后您可以拥有额外的特定客户(在这种情况下为 65)。
My (subselect sqlvars) pre-creates variables applied for the query.我的(子选择 sqlvars)预先创建了应用于查询的变量。 It computes one month ago by subtracting 1 month from whatever the current date it.
它通过从当前日期减去 1 个月来计算一个月前。 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.