简体   繁体   中英

Count all rows and return values based on frequency

I want to do a query that will count all the 'email' rows in my table and return all the values based on frequency. I don't want to group the results though, I want to show every variation of the result, here is what I have so far, as you can see it sorts by frequency but merges them by group, I'd just prefer to show them all but in order of frequency.

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

SQL -

CREATE TABLE uploads 
(
 email varchar(200)
);

INSERT INTO uploads
(email)
VALUES
('test@email.com'),
('test@email.com'),
('test@email.com'),
('test2@email.com'),
('test2@email.com'),
('test3@email.com'),
('test4@email.com');

Here Is the result I'd like

|              EMAIL |
----------------------
|    test@email.com  |
|    test@email.com  |
|    test@email.com  |
|    test2@email.com |
|    test2@email.com |
|    test3@email.com |
|    test4@email.com |

You can join against a subquery that returns an aggregate COUNT() per email and order by the descending 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

Effectively, this produces a result like the following, though you don't actually include the num column in the SELECT list:

|              EMAIL | num |
----------------------------
|    test@email.com  | 3
|    test@email.com  | 3
|    test@email.com  | 3
|    test2@email.com | 2
|    test2@email.com | 2
|    test3@email.com | 1
|    test4@email.com | 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM