我有一个包含以下行的表:
key Name
1 Mighty
2 Jon
3 Jaine
4 Arya
现在,我要计算表中所有NAME
的第一个字符的每个不区分大小写的出现次数,然后按降序对结果进行排序。如果有平局(多个字符的数目相等),则应按字母顺序对结果进行排序,因此我的输出如下:
A 3
J 2
M 1
A
存在3次,在Jaine
中存在一次,在Arya
中存在两次。
答案 0 :(得分:1)
尝试这样
SELECT LEFT(Name,1) AS letter, COUNT(*) As ct
FROM Tbl
GROUP BY LEFT(Name,1)
ORDER BY ct DESC,letter
答案 1 :(得分:1)
尝试此选项:
SELECT LEFT(Name, 1) AS letter, COUNT(*) AS cnt
FROM your_table
GROUP BY LEFT(Name, 1)
ORDER BY COUNT(*) DESC, letter;
请注意,如果两个或两个以上的字母具有相同的计数,则ORDER BY
子句首先按计数降序排序,然后按首字母排序。
答案 2 :(得分:1)
此代码产生预期的结果。经过SQL Fiddle测试。假定数据存储在表table1
中:
with first_letters as
(
select
upper(left(Name,1)) as letter_uppercase,
count(*) as count_ignore
from table1
group by upper(left(Name,1))
),
occurrences as (
select
t1.Name,
length(t1.Name) - length(replace(upper(t1.Name), fl.letter_uppercase,'')) as occurrence
from table1 t1
inner join first_letters fl on fl.letter_uppercase = upper(left(t1.Name,1))
)
select
result.letter_uppercase,
sum(result.occurrence) as sum_occurrence
from
(
select
fl.letter_uppercase,
o.occurrence
from first_letters fl
inner join occurrences o on upper(o.Name) like '%' || fl.letter_uppercase || '%'
) result
group by result.letter_uppercase
order by sum(result.occurrence) desc,
result.letter_uppercase;
答案 3 :(得分:0)
您需要首先创建表中所有字符的列表,然后创建所有前一个字符的列表,然后将它们组合:
with all_chars as (
select c
from names, unnest(string_to_array(lower(name), null)) as t(c)
), first_chars as (
select distinct lower(left(name,1)) as c
from names
)
select fc.c,
(select count(*) from all_chars ac where ac.c = fc.c) as cnt
from first_chars fc
order by cnt desc, fc.c;