问题描述
Name Age
chethan 27
Sanjay 25
Radha 54
Chethan 27
Radha 54
chethan 27
chethan 27
chethan 27
Radha 54
输出应该像
Name Age
chethan 27
Radha 54
Sanjay 25
这样的顺序是这样的,Chethan在顶部,因为它出现的次数最多,而Sanjay出现的次数最少。我应该能够为此编写一个SQL查询。
我尝试使用distict,但没有得到合适的结果
解决方法
使用group by
并按count(*)
排序
select name,age from tablename
group by name,age
order by count(*) desc
,
实际上,结果却有所不同。
除了4个出现的“ chethan”和一个小“ c”之外,您还有1个出现的“ Chethan”。
WITH
input(Name,Age) AS (
SELECT 'chethan',27
UNION ALL SELECT 'Sanjay',25
UNION ALL SELECT 'Radha',54
UNION ALL SELECT 'Chethan',27
UNION ALL SELECT 'Radha',54
UNION ALL SELECT 'chethan',27
UNION ALL SELECT 'chethan',27
UNION ALL SELECT 'Radha',54
)
SELECT
name,age
FROM input
GROUP BY
name,age
ORDER BY count(*) DESC;
-- out name | age
-- out ---------+-----
-- out chethan | 27
-- out Radha | 54
-- out Sanjay | 25
-- out Chethan | 27