重复序列号和重复序列号

时间:2014-04-08 02:03:37

标签: mysql sql sql-server sql-server-2008 tsql

每个患者都应该有唯一的randomID,这些randomID应该按顺序排列,所以我应该这样做 带回(Duplicate RandomID)和(Out of Sequence RandomID)

这是我的查询

declare @valueCheck table
(RowNumber Int Identity
,PatientID varchar(25)
,RandomID varchar(25))

insert into @ValueCheck
(PatientID, RandomID)

select
PatientID
, RandomID

From   dbo.CurrentData

where QuestionID= 200
order by patientid, RandomID 

如果我应用这个条件,我会得到(不按顺序的RandomID)

Select s1.PatientID, s1. RandomID as OutOFSequence
From @ValueCheck s1
Left Join @ValueCheck s2
On s1.RandomID = s2.RandomID – 1
Where s2.RandomID is Null

如果我应用这个,我会得到(Duplicate RandomID)

select * from @ValueCheck
where RandomID in 
(Select RandomID
From @ValueCheck
Group by RandomID
Having Count(RandomID) > 1)

我想要的是,我想要一张将两种条件结合在一起的表

1 个答案:

答案 0 :(得分:1)

为什么不进行联合查询。

Select s1.PatientID, s1. RandomID, 'OutOFSequence'
From @ValueCheck s1
Left Join @ValueCheck s2
On s1.RandomID = s2.RandomID – 1
Where s2.RandomID is Null
union all
select PatientID, RandomID, 'Duplicate' from @ValueCheck
where RandomID in 
(Select RandomID
From @ValueCheck
Group by RandomID
Having Count(RandomID) > 1)