我添加了一张我遇到的照片。突出显示的是我需要抓住的,带删除线的那些是我不需要的。所以第一个胆小者(561346)没有6个月的间隔,所以我希望所有这些行。第二个Tempid(661450)在第9行有6个月的间隔,所以我只想要下一个(第10行)该不需要的那个剩余的那行。 Last tempid(662020)在第16行有8个月的间隙,然后在其后还有4行。我只想抓住那4行。我希望这是有道理的。
我只需要一个人来帮助我。我已经尝试了好几天了。
WITH cte AS
(
SELECT pt.TempID, MIN(pt.InvoiceDate) AS 'min', MAX(pt.InvoiceDate) AS
'Max',
pt.JobNumber ,
ROW_NUMBER() OVER (PARTITION BY tempid ORDER BY MAX(pt.InvoiceDate)) AS
'Row'
FROM #temp t
JOIN pamwebhouse..pamtempjobs pt
ON SUBSTRING(t.EMPLOYEE, 5,10) = pt.TempID
WHERE
pt.Status <> 'Posted'
AND pt.PayTypeID IN ('Regul','OT','Sick')
GROUP BY pt.TempID, pt.jobnumber
)
SELECT a.TempID, a.JobNumber,DATEDIFF(month, a.max, a.start) AS 'Diff' ,
A.MAX
, a.Row
INTO #temp2
FROM (
SELECT c.TempID, c.JobNumber, c.min AS 'Min', c.max AS 'Max',
CASE WHEN c2.TempID IS NULL THEN NULL ELSE c2.min END AS 'Start', c.Row
FROM cte c
LEFT JOIN cte c2
ON c2.row = c.Row +1
AND c.TempID = c2.TempID
--ORDER BY c.TempID
) a
ORDER BY a.TempID
--This is what is giving me the output in the screenshot.
select t.tempid, t.JobNumber, test AS 'Gap',row,
max(case when test >= 6 then jobnumber END) over (PARTITION BY
tempid ORDER by max) as id_6
from #temp2 t
答案 0 :(得分:0)
您可以使用窗口功能:
select t.*
from (select t.*,
max(case when gap = 6 then row end) over (partition by tempid order by row) as seq
from table t
) t
where (t.gap <> 6 and t.seq is not null);