查找在每个站点上访问过至少两个不同国家的唯一身份用户数。 给定时间戳记,用户,国家/地区,站点
我认为查询应该看起来像这样,但它似乎不正确,因为它对每个站点的唯一身份用户数量给出了非常相似的答案。
SELECT site_id, COUNT (DISTINCT user_id)
FROM SWE
GROUP BY site_id
HAVING COUNT(country_id) >=2
ORDER BY site_id ASC;
答案 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