【问题标题】:How do I determine the category with the highest count within a group?如何确定组内计数最高的类别?
【发布时间】:2020-09-16 01:54:15
【问题描述】:
select substr(shopabb, 1, 4) as shopgroup, count(*)
from table
where shopabb like'h%'
group by substr(shoppabb, 1, 4)
order by count(*) DESC;

我在子字符串组中计算表中的所有商店缩写。我有另一个名为 city 的列,显示商店缩写的位置。现在我还想选择/显示子字符串组最常出现的城市,如果可能的话,还要选择该城市的shopabb计数。结果应该是这样的:

    shopabb   Count(*)   City      Count_City
    -----------------------------------------
   hel         50         London    40
   heal        20         Berlin    15   
   hot         10         Rome       8

谢谢!

【问题讨论】:

    标签: sql sqlite group-by count


    【解决方案1】:

    row_number() 与两级聚合一起使用:

    select shopgroup, sum(cnt) as total_count, 
           max(case when seqnum = 1 then city end) as city_with_max,
           max(case when seqnum = 1 then cnt end) as cnt_at_max
    from (select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt,
                 row_number() over (partition by substr(shopabb, 1, 4) order by count(*) desc) as seqnum
          from table
          where shopabb like'h%'
          group by substr(shopabb, 1, 4), city
         ) t
    group by shopgroup
    order by sum(cnt) DESC;
    

    Here 是一个 dbfiddle,说明语法有效。

    编辑:

    你可以不使用窗口函数来做到这一点,但是要麻烦得多:

    select substr(shopabb, 1, 4) as shopgroup, city, count(*) as cnt
    from table t
    where shopabb like'h%'
    group by substr(shoppabb, 1, 4), city
    having count(*) = (select count(*)
                       from table t2
                       where substr(t2.shopabb, 1, 4) = substr(t.shopabb, 1, 4)
                       group by city
                       order by count(*) desc
                       limit 1
                      );
    

    请注意,如果两个城市的最大值相同,这将返回重复项。还需要做更多的工作才能获得总体总数。

    【讨论】:

    • [09:37:54] 在数据库“表”上执行 SQL 查询时出错:靠近“(”:语法错误。我认为分区前的括号是问题所在。
    • @remotesatellite 。 . .语法错误是由您使用 table 来引用您的表格引起的。输入您的表名。我刚刚使用了您在问题中提供的内容。
    • 我替换了所有的列名和表名。但我仍然遇到同样的语法错误。
    • SQLite 从 3.25.0 版本开始支持窗口函数。当前版本是 3.32。也许您使用的是旧版本。
    • 我使用的是 3.22.0。这应该可以解释问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2013-07-17
    相关资源
    最近更新 更多