我有一个餐桌邀请,为每个用户保存他收到的电子邮件邀请。 一个用户可以拥有多封电子邮件,每封电子邮件上可以收到多封邀请。
create table invitation (
user_id INT NOT NULL,
email VARCHAR(32) NOT NULL
);
insert into invitation (user_id, email)
values
(3, '[email protected]'),
(3, '[email protected]'),
(3, '[email protected]'),
(1, '[email protected]'),
(1, '[email protected]'),
(1, '[email protected]'),
(1, '[email protected]'),
(2, '[email protected]'),
(2, '[email protected]'),
(1, '[email protected]'),
(1, '[email protected]'),
(2, '[email protected]'),
(2, '[email protected]');
我希望拥有最多邀请的顶级用户。但对于用户列表的完整情况:所有电子邮件和邀请计数器,除了邀请最大的电子邮件之外。我不需要只通过一次邀请来查看用户。
结果应该是这样的:
userId. email. counter of invitations per email
--------------------------------
1, '[email protected]', 4, <---- the biggest invitation number
1, '[email protected]', 2, <---- followed by the rest of invitations for same user
2, '[email protected]', 3, <---- next biggest invitation number
2, '[email protected]', 1. <---- followed by the rest of invitations for same user.
我尝试了使用 group by 和 order by 的 SQL SELECT 查询,但它显然更复杂。
谢谢。
SELECT user_id, email, count(*)
FROM #invitation
GROUP BY user_id, email
ORDER BY user_id, count(*) desc