【问题标题】:Find the number of unique users who have visited at least two different countries per site找出每个站点访问过至少两个不同国家的唯一用户数
【发布时间】:2019-05-15 14:42:13
【问题描述】:

找出每个网站至少访问过两个不同国家/地区的唯一用户数。 给定时间戳、用户、国家、站点

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

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

【问题讨论】:

    标签: mysql sql count distinct


    【解决方案1】:

    两级聚合是编写查询最自然的方式:

    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;
    

    【讨论】:

      【解决方案2】:

      试试这个-

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 2011-09-17
        • 2013-08-13
        • 1970-01-01
        相关资源
        最近更新 更多