按条件查找SQL Server中缺少的行
我试图找到两个参数化日期之间不存在的行 例如2010年1月1日和2011年1月1日按条件查找SQL Server中缺少的行,sql,sql-server,Sql,Sql Server,我试图找到两个参数化日期之间不存在的行 例如2010年1月1日和2011年1月1日 ID Date col 3 col 4 123 01/01/2010 x x 456 01/01/2010 x x 6578 01/01/2010 x x 123 01/03/2010 x x 456 01/03/2010 x x 6578 01/03/2010 x x 123 01/01/2011
ID Date col 3 col 4
123 01/01/2010 x x
456 01/01/2010 x x
6578 01/01/2010 x x
123 01/03/2010 x x
456 01/03/2010 x x
6578 01/03/2010 x x
123 01/01/2011 x x
456 01/01/2011 x x
789 01/01/2011 x x
123 01/01/2012 x x
456 01/01/2012 x x
789 01/01/2012 x x
我想返回:
ID Date col 3 col 4
6578 01/01/2010 x x
789 01/01/2011 x x
所以在伪代码中
If Id exists for 01/01/2010 but not 01/01/2011, return result
AND
If Id exists for 01/01/2011 but not 01/01/2010, return result
如果要查找只出现一次的行,则此操作将起作用:
select *
from (select t.*,
count(*) over (partition by id) as NumYears
from t
) t
where NumYears = 1
也许更一般的形式是:
select *
from t
where t.id in (select id
from t
group by id
having (max(case when year(date) = 2010 then 1 else 0 end) = 1 and
max(case when year(date) = 2011 then 1 else 0 end) = 0
) or
(max(case when year(date) = 2010 then 1 else 0 end) = 0 and
max(case when year(date) = 2011 then 1 else 0 end) = 1
)
)
首先,你的逻辑不确定。现在试试这个。这是你的电话号码
我不明白你想做什么。返回的行位于上面的数据库中。如果查看ID 456和789,唯一的区别是ID。是否要返回每个日期ID最高的行?如果这些年中有其他年份或其他日期,该怎么办?我希望能够设置比较之间的确切日期。@jedd。我想你应该问另一个问题,更好地解释你想要什么。我的头脑很清楚:我想现在我已经编辑清楚了!谢谢Gordon…但这对我的“更清晰”的例子不起作用它怎么不起作用?有一个额外的括号,但删除后,查询将执行您想要的操作。
;with cte as
(
select id
from t
group by id
having count(id) = 1
)
select t.id, t.date, t.col3, t.col4
from t join cte on t.id = cte.id
--Results
ID DATE COL3 COL4
789 2011-01-01 x x
6578 2010-01-01 x x