我正在编写一个查询,根据加载日期读取一个表中的数据。主要过程是检查从最近的加载日期到表中是否有任何内容与整个表的历史记录相比。我遇到的问题是对多列使用'Not Exists'语句时。它会检查指定的列是否单独存在而不是作为一组列存在。正如在下面的代码中列出的那样,SQL检查是否在表之间不存在姓氏,名字和中间名,而不是全部为一个(几乎就像它使用'OR'而不是'AND'一样第二个问题。任何建议,还是我应该走另一条路?
SELECT DISTINCT
[Last Name] ,
[First Name] ,
[Middle Name]
INTO #B
FROM A
WHERE Load_Date = ( SELECT MAX(Load_Date)
FROM A
)
SELECT DISTINCT
[Last Name] ,
[First Name] ,
[Middle Name]
FROM A
WHERE NOT EXISTS ( SELECT [Last Name] ,
[First Name] ,
[Middle Name]
FROM #B B
WHERE A.[Last Name] = B.[Last Name]
AND A.[First Name] = B.[First Name]
AND A.[Middle Name] = B.[Middle Name] )
AND Load_Date <> ( SELECT MAX(Load_Date)
FROM A
)
答案 0 :(得分:0)
您似乎想要获取不在上次加载中的名称组合。这是一种更简单的方法:
Select [Last Name], [First Name], [Middle Name]
from A
group by [Last Name], [First Name], [Middle Name]
having max(Load_Date) < (Select Max(Load_Date) From A);
您的查询应该有效。我认为你误解了not exists
的工作原理。
答案 1 :(得分:0)
SELECT [Last Name], [First Name], [Middle Name]
FROM A
WHERE [Load_Date] = (SELECT MAX([Load_Date]) From A)
EXCEPT
SELECT [Last Name], [First Name], [Middle Name]
FROM A
WHERE [Load_Date] <> (SELECT MAX([Load_Date]) From A)