我有下表,我想写一个优化的查询:
Id Name Department
--------------------------------
1 Ojas Soft Engineer
2 Amy Marketing
3 Aditya Networking
4 Riya Admin
5 Ojas Manager
6 Riya Receptionist
我需要输出:
Id Name Department Name repeat count
------------------------------------------------
1 Ojas Soft Engineer 2
2 Amy Marketing 1
3 Aditya Networking 1
4 Riya Admin 2
5 Ojas Manager 2
6 Riya Receptionist 2
我的查询:
SELECT
Id, Name, Department, COUNT(*) as RepeatNameCount
FROM
Email
GROUP BY
Name
但我想要返回每一行。我的问题有时在网格中只返回10行,但是对于所有可用数据,应返回重复的名称数
答案 0 :(得分:3)
另一个选项是窗口功能
Select *
,RepeatCnt = sum(1) over (partition by Name)
From Email
完全披露:我怀疑scaisEdge的方法更具性能
答案 1 :(得分:1)
您可以在子查询上使用具有受约束结果的连接
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
答案 2 :(得分:0)
您可以使用窗口功能或subquery
select *,
count(*) over (partition by name) RepeatNameCount
from email e;
或者您也可以使用subsquery
select *,
(select count(*) from email where name = e.name) RepeatNameCount
from email e;
答案 3 :(得分:0)
选择ID,姓名,部门, (从电子邮件x中选择计数(*),其中x.name = y.name group by x.name)为Repeat_Name_Count 来自电子邮件y;