查找每个站点访问过至少两个不同国家的唯一身份用户数

时间:2019-05-15 14:42:14

标签: mysql sql count distinct

查找在每个站点上访问过至少两个不同国家的唯一身份用户数。 给定时间戳记,用户,国家/地区,站点

我认为查询应该看起来像这样,但它似乎不正确,因为它对每个站点的唯一身份用户数量给出了非常相似的答案。

SELECT site_id, COUNT (DISTINCT user_id) 
FROM SWE 
GROUP BY site_id
HAVING COUNT(country_id) >=2
ORDER BY site_id ASC;

2 个答案:

答案 0 :(得分:3)

两个级别的聚合是编写查询的最自然的方法:

select site_id, count(*)
from (select user_id, site_id, count(*)
      from swe
      group by user_id, site_id
      having min(country) <> max(country)  -- or count(distinct country) >= 2
     ) us
group by site_id;

答案 1 :(得分:1)

尝试一下-

SELECT A.user_id,B.site_id,COUNT(DISTINCT B.country_id) [Country Visited]
FROM
(
    SELECT user_id 
    FROM SWE
    GROUP BY user_id
    HAVING COUNT(site_id) = COUNT(DISTINCT site_id)
)A
INNER JOIN SWE B ON A.user_id = B.user_id
GROUP BY A.user_id,B.site_id
HAVING COUNT(DISTINCT B.country_id) >= 2