如何仅对一列使用“不同”?

我有一个查询,它从一些“位置”表中检查访问。如果用户使用“ emp”或“ oth”的引荐进行了注册,则不应计入其首次访问,但应计入第二次访问和转发。

我正在尝试计算每个位置的“首次访问”次数。每当他们去拜访时,我都会得到一个记录,记录在哪个位置。

问题是我的查询计数正确,但是某些用户访问了不同的位置。因此,不只是计算该位置的访问次数(第一个),而是在用户访问过的每个位置添加一个访问次数。

这是我的查询

SELECT COUNT(DISTINCT CASE WHEN customer.ref IN ('emp','oth') THEN customer.id END) as visit_count,locations.name as location FROM locations
LEFT JOIN visits ON locations.location_name = visits.location_visit_name
LEFT JOIN customer ON customer.id = visits.customer_id
WHERE locations.active = true
GROUP BY locations.location_name,locations.id;

我得到的结果是

visit_count |  locations
-------------------------
    7       |      Loc 1
    3       |      Loc 2
    1       |      Loc 3

应该如何:

visit_count |  locations
-------------------------
    6       |      Loc 1
    2       |      Loc 2
    1       |      Loc 3

因为这些人中有2人在这两个地点都有访问,所以每个地点都算一次。我认为DISTINCT也在位置上做到这一点,只应在customer.id

是否可以在查询中添加一些内容,以便仅获取第一次访问的位置,而无需关心他们是否在其他位置进行了其他访问?

cdau9874 回答:如何仅对一列使用“不同”?

尝试在where子句中移动when条件

SELECT COUNT( distinct customer.id)  as visit_count,locations.name as location 
FROM locations
LEFT JOIN visits ON locations.location_name = visits.location_visit_name
LEFT JOIN customer ON customer.id = visits.customer_id
WHERE locations.active = true
  AND customer.ref IN ('emp','oth')
GROUP BY locations.location_name;c
,

如果我正确地关注了您,那么您只想计算每个客户的首次访问量(按位置分布)。

一种解决方案是在相关on的{​​{1}}子句中使用相关子查询来过滤首次访问客户。假设join列存储了每次访问的日期,您可以执行以下操作:

visit(visit_date)

旁注:

  • 在每个客户的首次访问时适当地拟合,从而避免了select count(c.customer_id) visit_count,l.name as location from locations l left join visits v on l.location_name = v.location_visit_name and v.visit_date = ( select min(v1.visit_date) from visit v1 where v1.customer_id = v.customer_id ) left join customer c on c.id = v.customer_id and c.ref in ('emp','oth') where l.active = true group by l.location_name,l.id; 聚合函数中对distinct的需求

  • 表别名使查询更简洁,更易于理解;我建议在所有查询中使用它们

  • 与作为条件计数标准相比,count()上的过滤器最好放在customer(ref)子句中

本文链接:https://www.f2er.com/3164047.html

大家都在问