簡體   English   中英

如何編寫查詢以刪除重復項並根據 SQL 中的頻率對表進行排序?

[英]How to write a Query to remove duplicates and sort the table as per the frequency in SQL?

考慮我有一張這樣的桌子:

Name        Age 
chethan      27
Sanjay       25      
Radha        54
Chethan      27
Radha        54
chethan      27
chethan      27
chethan      27
Radha        54

output 應該像

Name        Age 
chethan      27
Radha        54
Sanjay       25  

這個順序是這樣的,Chethan 在頂部,因為它出現的次數最多,而 Sanjay 出現的次數最少。我應該可以寫一個 SQL 查詢。

我嘗試使用 Disct,但沒有得到合適的結果

使用group by和 order by count(*)

select name,age from tablename
group by name, age 
order by count(*) desc

實際上,結果證明是不同的。

除了出現 4 次帶有小“c”的“chethan”之外,您還出現了 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 '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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM