我需要查询具有以下格式并期望提供结果的单个表。由于ID验证和注册的状态是在同一天,因此应该忽略它,并且应该返回其他ID
表1
ID Status Date
123 Validated 2/3/2016
123 Registered 2/3/2016
234 Validated 2/5/2016
234 Registered 2/7/2016
345 Validated 2/6/2016
456 Registered 2/9/2016
结果
ID Status Date
234 Registered 2/7/2016
456 Registered 2/9/2016
答案 0 :(得分:2)
这是一个使用连接的选项(有一些样本数据用于测试):
create table #table1 (id int, stat varchar(20), dt date)
insert into #table1 values(123 ,'Validated', '2/3/2016')
insert into #table1 values(123 ,'Registered', '2/3/2016')
insert into #table1 values(234 ,'Validated', '2/5/2016')
insert into #table1 values(234 ,'Registered', '2/7/2016')
insert into #table1 values(345 ,'Validated', '2/6/2016')
insert into #table1 values(456 ,'Registered', '2/9/2016')
Select a.*
from #table1 a
left join #table1 b
on a.id = b.id
and a.dt = b.dt
and b.stat <> 'Registered'
where a.stat = 'Registered' and b.stat is null
答案 1 :(得分:0)
嗯。一种方法使用窗口函数:
select t.*
from (select t.*, min(status) over (partition by id, date) as mins,
max(status) over (partition by id, date) as maxs
from t
) t
where mins = maxs;
这将返回每个日期只有一个状态的记录。
答案 2 :(得分:0)
另一种方法是通过像<; p>这样的子查询
select t.*
from tbl t
where Status = 'Registered'
and Date not in (
select date from tbl
where Status = 'Validated'
)
答案 3 :(得分:0)
SELECT *
FROM table
WHERE [Status] = 'Registered'
AND ID NOT IN (SELECT ID FROM table GROUP BY ID, [Date] HAVING COUNT(ID) > 1)
答案 4 :(得分:0)
Select r.*
from table1 r
left join table1 v
on v.id = r.id
and v.[date] = r.[date]
and v.stat ='Validated'
where r.stat = 'Registered'
and v.id is null
与aph +1相同很多