我在下面有一张桌子。每天将运行3个不同的文件,状态将作为成功/失败插入到表中。我需要状态成功的所有3个文件并获取该日期。如下表所示,SQL查询必须返回Date 2020-02-25(因为所有3个文件都成功)
请帮助我进行查询,我尝试了很多查询,但无法获得所需的结果。
ID Pipeline_name Status UpdatedDate
1 Student_Dump SUCCESS 2020-02-27
2 Teacher_Dump SUCCESS 2020-02-27
3 Subjects_Dump Failed 2020-02-27
4 Student_Dump SUCCESS 2020-02-26
5 Teacher_Dump Failed 2020-02-26
6 Subjects_Dump SUCCESS 2020-02-26
7 Student_Dump SUCCESS 2020-02-25
8 Teacher_Dump SUCCESS 2020-02-25
9 Subjects_Dump SUCCESS 2020-02-25
答案 0 :(得分:2)
尝试这个:
WITH cteStatus AS(
SELECT UpdatedDate, Status, ROW_NUMBER() OVER (PARTITION BY UpdatedDate, Status ORDER BY UpdatedDate, Status) rn
FROM T1
)
SELECT c.UpdatedDate
FROM cteStatus c
WHERE Status = N'SUCCESS'
AND rn = 3
想法是获取所有日期,其中每个日期都有“状态成功”的三个记录。
这里是Fiddle的链接:http://sqlfiddle.com/#!18/a25c2b/5/1
答案 1 :(得分:1)
您可以使用Rownumber()
来实现
Select ID,Pipeline_name,Status,UpdatedDate
from
(
select *,row_number() over(partition by Status,UpdatedDate order by id) as rn
from #table1
)A where rn=3 and Status = 'SUCCESS'
已更新
如果仅需要最新数据日期,则可以选择TOP 1
与ORDER BY ID DESC
组合
Select TOP 1 ID,Pipeline_name,Status,UpdatedDate
from
(
select *,row_number() over(partition by Status,UpdatedDate order by id) as rn
from #table1
)A where rn=3 and Status = 'SUCCESS'
ORDER BY ID DESC
答案 2 :(得分:0)
您可以使用row_number()
Select * from
(
select *,row_number() over(parition by updatedate,pipeline_name order by id) as rn
from tablename
where status='SUCCESS'
)A where rn=1
答案 3 :(得分:0)
您可以进行聚合:
select UpdatedDate
from table t
group by UpdatedDate
having sum(case when statue = 'failed' then 1 else 0 end) = 0 and
count(distinct Pipeline_name) = 3;
答案 4 :(得分:0)
尝试一下:
select UpdatedDate from test where UpdatedDate not in
(select UpdatedDate from test where status='Failed');