2012-09-07 84 views
2

我想要執行一個查詢,它將計算我表中的所有「電子郵件」行,並根據頻率返回所有值。我不希望對結果進行分組,但我想要顯示結果的每個變體,這裏是我迄今爲止的內容,因爲您可以看到它按頻率分類,但按分組合並,我只想顯示他們都按照頻率排列。根據頻率計算所有行並返回值

select email 
from uploads 
group by email 
order by count(*) desc 

SQL -

CREATE TABLE uploads 
(
email varchar(200) 
); 

INSERT INTO uploads 
(email) 
VALUES 
('[email protected]'), 
('[email protected]'), 
('[email protected]'), 
('[email protected]'), 
('[email protected]'), 
('[email protected]'), 
('[email protected]'); 

這裏是我想

|    EMAIL | 
---------------------- 
| [email protected] | 
| [email protected] | 
| [email protected] | 
| [email protected] | 
| [email protected] | 
| [email protected] | 
| [email protected] | 

回答

5

你可以參加對抗由遞減的計數返回每封郵件和秩序的聚集COUNT()子查詢的結果:

SELECT 
    uploads.EMAIL 
FROM 
    uploads 
    JOIN (
    /* subquery returns distinct emails and their aggregate COUNT() */ 
    /* JOIN matches every row in `uploads` to the email and count */ 
    SELECT EMAIL, COUNT(*) as num FROM uploads GROUP BY EMAIL 
) c ON uploads.EMAIL = c.EMAIL 
ORDER BY 
    c.num DESC, 
    EMAIL ASC 

實際上,這會產生一個結果類似以下,但你實際上並不包括在SELECT列表中num柱:

|    EMAIL | num | 
---------------------------- 
| [email protected] | 3 
| [email protected] | 3 
| [email protected] | 3 
| [email protected] | 2 
| [email protected] | 2 
| [email protected] | 1 
| [email protected] | 1 
+0

謝謝主席先生!我會盡可能地接受你的答案。 – Adam