我需要一些帮助来编写 sql 代码到 return 按频率排序的客户数据项列表(从高到低)

I'd like some help to write sql code to return a list of customer data items ranked by frequency (high to low)

我正在查询的 table 有几千行和许多字段 - 我希望代码 return 少数字段的前 10 个值,即:名字,姓氏和城市 - 我还想查看值 returned.

的计数

例如

Ranking Forename FName Frequency Surname SName Frequency City City Frequency
1 Liam 830,091 Smith 2,353,709 New York 2,679,785
2 Mary 708,390 Johnson 1,562,990 Los Angeles 413,359
3 Noah 639,592 Williams 792,306 Chicago 393,511
4 Patricia 568,410 Brown 743,346 Houston 367,496
5 William 557,049 Jones 633,933 Phoenix 336,929
6 Linda 497,138 Miller 503,523 Philadelphia 304,638
7 James 490,665 Davis 503,115 San Antonio 255,142
8 Barbara 418,312 Garcia 468,683 San Diego 238,521
9 Logan 399,947 Rodriguez 461,816 Dallas 232,718
10 Elizabeth 399,737 Wilson 436,843 San Jose 213,483

returned 列表应该这样解释: table 中最常出现的名字是 Liam——有 830,091 个实例, 出现频率第五高的名字是 William——有 557,049 次出现, 第八大最常出现的城市是圣地亚哥——有 238,521 个实例 ...等等

(N.b。table 并未显示纽约有 270 万利亚姆 - 只是整个 table 中有 830,091 利亚姆 - 而且有 2,679,785整个纽约地址 table)

以下生成我需要的内容 - 但仅针对第一个字段(名字) - 我希望能够对三个字段执行相同的操作

SELECT Forename, COUNT(Forename) AS FName_Frequency
FROM Customer_Table
GROUP BY Forename
ORDER BY FName_Frequency DESC
limit 10

感谢期待

我会把它放在不同的行中:

select 'forename', forename, count(*) as freq
from customer_table
group by forename
order by freq desc
fetch first 10 rows only
union all
select 'surname', surname, count(*) as freq
from customer_table
group by surname
order by freq desc
fetch first 10 rows only
union all
select 'city', city, count(*) as freq
from customer_table
group by city
order by freq desc
fetch first 10 rows only;

请注意,这使用标准 SQL 语法,因为您没有使用您正在使用的数据库标记问题。您也可以将其放在单独的列中,使用:

select max(case when which = 'forename' then col end),
       max(case when which = 'forename' then freq end),
       max(case when which = 'surname' then col end),
       max(case when which = 'surname' then freq end),
       max(case when which = 'city' then col end),
       max(case when which = 'city' then freq end)
from ((select 'forename' as which, forename as col, count(*) as freq,
              row_number() over (order by count(*) desc) as seqnum
       from customer_table
       group by forename
      ) union all
      (select 'surname' as which, surname, count(*) as freq
              row_number() over (order by count(*) desc) as seqnum
       from customer_table
       group by surname
      ) union all
      (select 'city', city, count(*) as freq,
              row_number() over (order by count(*) desc) as seqnum
       from customer_table
       group by city
      )
     ) x
group by seqnum;