【问题标题】:Presto SQL - distinct in selective group byPresto SQL - 在选择性分组中不同
【发布时间】:2019-11-21 00:13:34
【问题描述】:
ID  Name     Gender  Country 
1   Arun     Male    India
2   Akshay   Male    England
3   Chethna  Female  India
4   Priya    Female  China
5   Piyush   Male    India
6   Arun     Male    England
7   Tisha    Female  England
8   Chethna  Female  China

我想先将他们分为男性/女性,然后是相关的国家/地区。

Query1 : select Gender, count(distinct name) from Table group by Gender

Output: 
Gender   count(distinct name)
Male     3
Female   3

像这样以 JSON 格式复制结果, 结果:{男:{count:3},女:{count:3}}

Query2 : select Gender, Country, count(distinct name) from Table group by Gender, Country

Output:
Gender  Country    count(distinct name)
Male    India      2
Male    England    2
Female  India      1
Female  China      2
Female  England    1

在上面的Json中加入这个结果,

结果:{男:{count:3,印度:{count:2},英格兰:{count:2}},女:{count:3,印度:{count:1},中国:{count: 2},英格兰:{count:1}}}

那么我可以在单个查询中实现这一点吗?

【问题讨论】:

    标签: presto


    【解决方案1】:

    您可以使用GROUPING SETS 在单个查询中按性别和按性别+国家/地区计算计数:

    WITH data(id, name, gender, country) AS (
       VALUES
       (1, 'Arun',    'Male'  , 'India'),
       (2, 'Akshay',  'Male'  , 'England'),
       (3, 'Chethna', 'Female', 'India'),
       (4, 'Priya',   'Female', 'China'),
       (5, 'Piyush',  'Male'  , 'India'),
       (6, 'Arun',    'Male'  , 'England'),
       (7, 'Tisha',   'Female', 'England'),
       (8, 'Chethna', 'Female', 'China'))
    
    SELECT gender, country, count(distinct name)
    FROM data
    GROUP BY GROUPING SETS ((gender), (gender, country))
    

    产生:

     gender | country | _col2
    --------+---------+-------
     Male   | England |     2
     Female | China   |     2
     Male   | NULL    |     3
     Female | NULL    |     3
     Female | India   |     1
     Male   | India   |     2
     Female | England |     1
    (7 rows)
    

    【讨论】:

    • 这也相当于GROUP BY ROLLUP (gender, country),对吧?
    • 差不多。 Rollup 还进行全局聚合。
    猜你喜欢
    • 2016-10-06
    • 2020-11-07
    • 2021-10-20
    • 2021-12-05
    • 2014-02-19
    • 2022-01-11
    • 2023-03-02
    • 2020-05-27
    • 2020-06-25
    相关资源
    最近更新 更多