查找缺失行的 SQL 查询返回语法错误
Posted
技术标签:
【中文标题】查找缺失行的 SQL 查询返回语法错误【英文标题】:SQL Query to find missing rows returns syntax error 【发布时间】:2016-02-23 07:57:41 【问题描述】:我尝试从两个向量中过滤缺失值。我尝试比较两个分别运行良好的查询。但是,将它们放在一起时,我似乎错过了一些东西:
SELECT ID_Name FROM [000_Skalar_Daten]
WHERE VertragsPool = 'Bestand'
AND Bilanzstichtag = '20151231'
AND VR_Key = '34'
AND Waehrung = 'EUR'
AND SII_LINE_OF_BUSINESS = 'KLV'
WHERE ID_Name NOT IN (
SELECT distinct VD.ID_Name
FROM [000_Vektor_Daten] VD
INNER JOIN [000_Skalar_Daten] SD
ON VD.VertragsPool = SD.VertragsPool
AND VD.ID_Name = SD.ID_Name
AND VD.Bilanzstichtag = SD.Bilanzstichtag
AND VD.VR_Key = SD.VR_Key
AND VD.Waehrung = SD.Waehrung
WHERE SD.VertragsPool = 'Bestand'
AND SD.Bilanzstichtag = '20151231'
AND SD.VR_Key = '34'
AND SD.Waehrung ='EUR'
AND SD.SII_LINE_OF_BUSINESS ='KLV'
)
在WHERE
子句附近返回语法错误。我的问题是如何重组查询以仅返回不在第二个查询部分中的值。也许我通过 MS Access 中的 pass-through-query 将此查询传递给 Microsoft SQL-Server 是相关的。
非常感谢!
【问题讨论】:
将第二个WHERE
替换为AND
。
另外,子查询中不需要SELECT DISTINCT
。
【参考方案1】:
错误的原因已经在 cmets 中提到过。这是编写查询的更好方法,它处理来自Sub-Query
的NULL
值
SELECT ID_Name
FROM [000_Skalar_Daten] a
WHERE VertragsPool = 'Bestand'
AND Bilanzstichtag = '20151231'
AND VR_Key = '34'
AND Waehrung = 'EUR'
AND SII_LINE_OF_BUSINESS = 'KLV'
AND NOT EXISTS (SELECT 1
FROM [000_Vektor_Daten] VD
INNER JOIN [000_Skalar_Daten] SD
ON VD.VertragsPool = SD.VertragsPool
AND VD.ID_Name = SD.ID_Name
AND VD.Bilanzstichtag = SD.Bilanzstichtag
AND VD.VR_Key = SD.VR_Key
AND VD.Waehrung = SD.Waehrung
WHERE SD.VertragsPool = 'Bestand'
AND SD.Bilanzstichtag = '20151231'
AND SD.VR_Key = '34'
AND SD.Waehrung = 'EUR'
AND SD.SII_LINE_OF_BUSINESS = 'KLV'
AND a.ID_Name = VD.ID_Name)
【讨论】:
以上是关于查找缺失行的 SQL 查询返回语法错误的主要内容,如果未能解决你的问题,请参考以下文章