我有一个带有ClaimNumber,NoteCreateDate,NoteType
的表我想找到包含“已发送评论”等声明的声明。在NoteCreateDate
中没有间隙地背靠背例如。
+-------------+----------------+--------------------+----------+
| ClaimNumber | NoteCreateDate | Notes | NoteType |
+-------------+----------------+--------------------+----------+
| 12121 | 12/01/2017 | ReviewSent | Subject |
| 12121 | 12/05/2017 | PackagesenttoABC | Details |
| 12121 | 12/07/2017 | ReviewSent | Subject |
| 10005 | 05/06/2018 | ReviewSent | Subject |
| 10005 | 05/07/2018 | ReviewSent | Subject |
| 10005 | 05/08/2018 | ReviewSent | Subject |
| 10005 | 05/12/2018 | Fieldinvestigation | SIU |
+-------------+----------------+--------------------+----------+
预期 在此示例中,我只想要声明号 10005 ,因为声明中包含“发送的评论”和“已发送的评论”。背靠背,日期没有间隙(连续日期)。例如,我想找到带有短语' ReviewSent'今天创建并且以下注释也应该相同'评论已发送',无论何时创建,可能是第二天甚至10天后...在此先感谢
我当前的MS SQL查询。
select cm.ClaimNum, a.NoteCreateDate, a.Notes, a.NoteType
from CMaster cm
left join Note a on cm.ClaimNum = a.PARENTREF
left join NoteType] b on b.ID = a.TYPECODE
where Body like '%Review Sent%'
答案 0 :(得分:1)
因此,如果您想要找回ReviewSent备注发回的ClaimNumber,那么此查询将获得它们
CREATE TABLE T1
([ClaimNumber] int, [NoteCreateDate] datetime, [Notes] varchar(18), [NoteType] varchar(7))
;
INSERT INTO T1
([ClaimNumber], [NoteCreateDate], [Notes], [NoteType])
VALUES
(12121, '2017-12-01 00:00:00', 'ReviewSent', 'Subject'),
(12121, '2017-12-05 00:00:00', 'PackagesenttoABC', 'Details'),
(12121, '2017-12-07 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-06 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-07 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-08 00:00:00', 'ReviewSent', 'Subject'),
(10005, '2018-05-12 00:00:00', 'Fieldinvestigation', 'SIU')
;
SELECT DISTINCT X.ClaimNumber
FROM(
SELECT
ClaimNumber
,NoteCreateDate
,Notes
,NoteType
,LD=LEAD( Notes )OVER(PARTITION BY ClaimNumber ORDER BY NoteCreateDate ASC)
FROM dbo.T1
) X WHERE LD= 'ReviewSent' AND X.Notes= 'ReviewSent'
DROP TABLE dbo.T1
结果
ClaimNumber
10005
答案 1 :(得分:0)
Select * into #tmp
from
(
Select 12121 as ClaimNumber,'12/01/2017' as
NoteCreateDate,'ReviewSent' as Notes,'Subject' as NoteType
union
Select 12121 , '12/05/2017' , 'PackagesenttoABC' , 'Details'
union
Select 12121 , '12/07/2017' , 'ReviewSent' ,
'Subject'
union
Select 10005 , '05/06/2018' , 'ReviewSent' , 'Subject'
union
Select 10005 , '05/07/2018' , 'ReviewSent' ,
'Subject'
union
Select 10005 , '05/08/2018' , 'ReviewSent' , 'Subject'
union
Select 10005 , '05/12/2018' , 'Fieldinvestigation' , 'SIU'
) t
/*create another temp table to simplify the query*/
Select * , ROW_NUMBER() OVER (PARTITION BY ClaimNumber ORDER BY
ClaimNumber)
as ClaimCounter into #tmp2 from #tmp
/** finally get the claimnos that have consecutive NoteCreate Date **/
SELECT distinct t1.ClaimNumber FROM #tmp2 t1
inner join #tmp2 t2 on (t1.ClaimCounter = t2.ClaimCounter - 1 and
t1.ClaimNumber = t2.ClaimNumber)
where
DATEDIFF(DAY,t1.NoteCreateDate,t2.NoteCreateDate) = 1
and
t1.Notes ='ReviewSent' and t2.Notes ='ReviewSent'