这是查询
select a.name,b.name,a.joining,b.joining from [SportsStore].[dbo].[Employees] a,
[SportsStore].[dbo].[Employees] b where a.joining = b.joining and a.name>b.name
然后突然出现了一个问题。我如何才能找到那些在不同日期被聘用的员工?我试过这样的事情
select a.name,b.name,a.joining,b.joining from [SportsStore].[dbo].[Employees] a,
[SportsStore].[dbo].[Employees] b where a.joining != b.joining and a.name>b.name
然后我意识到这没有意义。我想到了一个子查询,但它也不会工作,因为我们从两个表中选择。
所以我搜索了一下,找不到任何东西。
所以问题是我们如何“查找在不同加入日期雇用的员工姓名?”
答案 0 :(得分:1)
使用子查询加入Employees表,该子查询计算加入日期。
where j.num = 1
返回在不同日期雇用的员工
where j.num > 1
返回在同一日期雇用的员工
select e.id, e.name, e.joining
from [SportsStore].[dbo].[Employees] e
inner join (select joining, count(*) num
from [SportsStore].[dbo].[Employees]
group by joining) j
on j.joining = e.joining
where j.num = 1;
+----+------+---------------------+
| id | name | joining |
+----+------+---------------------+
| 1 | abc | 01.01.2017 00:00:00 |
+----+------+---------------------+
| 2 | def | 01.01.2017 00:00:00 |
+----+------+---------------------+
| 5 | mno | 01.01.2017 00:00:00 |
+----+------+---------------------+
+----+------+---------------------+
| id | name | joining |
+----+------+---------------------+
| 3 | ghi | 02.01.2017 00:00:00 |
+----+------+---------------------+
| 4 | jkl | 03.01.2017 00:00:00 |
+----+------+---------------------+
答案 1 :(得分:0)
如果您只需要名称(而不是不同的招聘日期列表),以下相当简单的查询应该可以完成这项工作:
select id, name
from employee
group by id, name
having count(distinct joining) > 1
答案 2 :(得分:0)
select name,joining from [SportsStore].[dbo].[Employees] where joining not in
(
select joining
from [SportsStore].[dbo].[Employees]
group by joining
having count(*)=1
)