具有较小值的SQLite百分比

时间:2018-05-16 03:10:04

标签: sql sqlite grouping percentage

所以我有这个用户和他们所在国家的用户表。

UserID | Name              | Country
-------+-------------------+------------
1      | Zaphod Beeblebrox | UK
2      | Arthur Dent       | UK
3      | Gene Kelly        | USA
4      | Nat King Cole     | USA

我需要按每个国家/地区的百分比生成所有用户的列表。我还需要将所有较小的成员国(低于1%)折叠成一个" OTHERS"类别。

我可以完成一个简单的"顶部x"成员琐碎的

SELECT COUNTRY, COUNT(*) AS POPULATION FROM SUBSCRIBERS GROUP BY COUNTRY ORDER BY POPULATION DESC LIMIT 10

并且可以通过PHP服务器端代码生成百分比,但我不太清楚如何:

  1. 在SQL中执行所有操作,包括直接在结果中进行百分比计算
  2. 俱乐部所有1%以下的会员都属于单一的其他类别。
  3. 所以我需要这样的东西:

    Country | Population
    --------+-----------
    USA     | 25.4%
    Brazil  | 12%
    UK      | 5%
    OTHERS  | 65%
    

    感谢帮助!

2 个答案:

答案 0 :(得分:0)

这是对此的查询,我使用子查询来计算总行数,然后使用它来获取每个行的百分比值。 “其他”类别是在单独的查询中生成的。行按降序排序,其他行排在最后。

SELECT * FROM 
    (SELECT country , ROUND((100.0*COUNT(*)/count_all),1) ||'%' AS population
     FROM (SELECT count(*) count_all FROM subscribers) AS sq,
     subscribers s
     WHERE (SELECT 100*count(*)/count_all 
            FROM subscribers s2 
            WHERE s2.country = s.country) > 1
     GROUP BY country
     ORDER BY population DESC)
UNION ALL
SELECT 'OTHERS', IFNULL(ROUND(100.0*COUNT(*)/count_all,1),0.0) ||'%' AS population
FROM (SELECT count(*) count_all FROM subscribers) AS sq,
     subscribers s
WHERE (SELECT 100*count(*)/count_all 
       FROM subscribers s2 
       WHERE s2.country = s.country) <= 1

答案 1 :(得分:0)

好的,我想我可能已经找到了一种方法来做到这一点,在执行速度上要快得多:

SELECT territory,
       Round(Sum(percentage), 3) AS Population
FROM (SELECT
           Round((Count(*)*100.0)/(SELECT Count(*) FROM subscribers),3) AS Percentage,
           CASE
             WHEN ((Count(*)*100.0)/(SELECT Count(*) FROM subscribers)) > 2 THEN
             country
             ELSE 'Other'
           END AS Territory
      FROM   subscribers
      GROUP  BY country
      ORDER  BY percentage DESC)
GROUP  BY territory
ORDER  BY population DESC;