用MIN和DISTINCT进行计数

时间:2019-10-27 01:23:46

标签: postgresql

我有一个查询,该查询返回一个月内用户访问的信息,但仅针对那些在该月前没有访问的用户。这次访问与一次访问的“位置”有关。

这是查询:

SELECT DISTINCT MIN(visits.cust_id), locations.name as location FROM visits
LEFT JOIN customer ON visits.id = customer.id
LEFT JOIN locations ON customer.location_id = locations.id
WHERE date_trunc('month', CURRENT_DATE) = date_trunc('month', visits.visit_date) AND (customer.referral = 'emp' OR customer.referral = 'oth')
AND NOT EXISTS (
  SELECT FROM visits
  WHERE id = customer.id
  AND date_trunc('month', CURRENT_DATE) > date_trunc('month', visits.visit_date)
  )
GROUP BY visits.visit_date, visits.cust_id, locations.name
HAVING count(visits.visit_date) = 1;

结果是:

cust_id |     location
---------------------
    1   |      Loc 1
    2   |      Loc 1
    3   |      Loc 1

在我的位置表上有3个,所以我想要的结果只是ID和位置名称的计数:

 cust_id  |   location
---------------------
  3       |    Loc 1
  0       |    Loc 2
  0       |    Loc 3

我知道我可以将整个查询包装成一个计数,并且可以对结果进行计数,但是它只给我3,这是正确的,但是我仍然需要将表与指示该计数所在的位置连接起来从并列出其他失踪人员。

1 个答案:

答案 0 :(得分:1)

WITH x AS (
    your_query_here
)
SELECT COUNT(x.cust_id), l.name
FROM locations l
LEFT JOIN x ON x.location = l.name
GROUP BY l.name

尽管,我建议您更改查询以返回在联接条件中使用此查询的位置的id。但这通常会给您带来结果。