我想进行查询,计算表格中的所有“电子邮件”行,并根据频率返回所有值。我不想对结果进行分组,我想显示结果的每个变体,这是我到目前为止所拥有的,因为你可以看到它按频率排序但是按组合并它们我只是喜欢显示它们除了按频率排列外。
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 |
答案 0 :(得分: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