3

我想做一个查询,计算我表中的所有“电子邮件”行,并根据频率返回所有值。我不想对结果进行分组,我想显示结果的每一个变化,这是我目前所拥有的,你可以看到它按频率排序,但按组合并,我只想显示它们都按频率顺序排列。

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');

这是我想要的结果

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

1 回答 1

6

您可以加入一个子查询,该查询返回每封电子邮件的聚合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

实际上,这会产生如下结果,尽管您实际上并未num在列表中包含该列SELECT

|              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
于 2012-09-07T15:42:12.170 回答