获取每组只有1条记录的记录

时间:2019-06-12 10:22:04

标签: sql sql-server

我们的出勤数据库数据如下(SQL Server)

empid       date          type
1           01-Jan         In
1           01-Jan         Out
2           01-Jan         In
3           01-Jan         In
3           01-Jan         Out

我们如何获取每位员工每个日期只有1条记录的记录(在上述情况下,01月1日为2)?

查询应仅列出一天中只有一种类型的员工的所有记录。

编辑

结果集应该更具体一些:显示所有仅在日期中“ In”但没有“ Out”的员工

5 个答案:

答案 0 :(得分:3)

使用Having

select empid, date, count(*)
from Mytable
group by empid, date
having count(*) = 1

您可以使用它来获取完整行:

select t1.*
from MyTable t1
inner join 
(
    select empid, date, count(*)
    from Mytable
    group by empid, date
    having count(*) = 1
) t2
on t1.empid = t2.empid
and t1.date = t2.date

答案 1 :(得分:2)

您可以使用窗口功能:

select t.*
from (select t.*,
             count(*) over (partition by empid, date) as cnt
      from t
     ) t
where cnt = 1;

您还可以使用聚合:

select empid, date, max(type) as type
from t
group by empid, date
having count(*) = 1;

答案 2 :(得分:1)

使用相关子查询

select * from tablename a
where not exists (select 1 from tablename b where a.empid=b.empid and  a.date=b.date and type='Out')

OR

select empid, date,count(distinct type)
from tablename
group by empid,date
having count(distinct type)=1

答案 3 :(得分:0)

解决方案非常简单,您可以使用“ DISTINCT”功能。 查询应为

SELECT DISTINCT empid FROM attendance

每位员工每个日期仅返回1条记录。

请参考-https://www.techonthenet.com/sql_server/distinct.php

答案 4 :(得分:0)

如果我们的ID也具有1 IN或1 OUT,这将起作用

Declare @t table (empid int,date varchar(50),types varchar(50))

insert into @t values (1,'01-Jan','IN')
insert into @t values (1,'01-Jan','OUT')
insert into @t values (2,'01-Jan','IN')
insert into @t values (3,'01-Jan','OUT')
insert into @t values (4,'01-Jan','OUT')

select * from @t a
where not exists (select 1 from @t b where a.empid=b.empid and a.types!=b.types)