简体   繁体   English

计算所有行并根据频率返回值

[英]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 - 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: 您可以加入一个子查询,该子查询返回每封电子邮件的聚合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: 实际上,这会产生如下结果,尽管您实际上并未在SELECT列表中包含num列:

|              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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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