sql - 找到 6 个月的差距并抓住一切 之后,如果没有 6 个月的差距,那么就抓住一切
问题描述
我添加了一张我遇到的图片。突出显示的是我需要抓取的那些,而带有删除线的是我不需要的。所以第一个 tempid (561346) 没有 6 个月的差距,所以我想要所有这些行。第二个 Tempid(661450) 在第 9 行有 6 个月的差距,所以我只想要下一个(第 10 行)其余行用于我不想要的那个 tempid。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
解决方案
您可以使用窗口功能:
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);
推荐阅读
- string - 如何键入包含少于 5 个字符的字符串并仍然继续下一行代码?
- bash - watch 命令不适用于特殊字符和引号
- angular - Angular 2+缓存的HTTP请求强制重新加载
- linux - 为什么在我的 fuse 文件系统中使用 ls 命令时会出现输入/输出错误?
- javascript - 删除 JavaScript 中的一些元素
- reactjs - 返回值并打印
零件 - deep-learning - 困惑:CNN的图像标记用于训练的目的是什么?
- c99 - 为什么使用 C99 时clock_gettime 无法编译?
- python - 对象键标签的计数
- python - Pyspark 模式:如何检查可空性?