在此查询中何处放置CASE WHEN列IS NULL

时间:2013-09-10 14:02:06

标签: sql ms-access null case

我在将MS Access查询转换为SQL时遇到了一些问题:

SELECT id, col1, col2, col3
FROM table1

LEFT OUTER JOIN table2
ON table1.id = table2.id

LEFT OUTER JOIN table3
ON table1.id = table3.id

到目前为止一切顺利,但这是我被卡住的(CASE)部分:

CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4

我知道上面这行不起作用,但希望它暗示我正在努力实现的目标。谢谢!

更新:到目前为止,所有建议都导致“关键字'AS'附近的语法不正确”错误,所以也许还有其他我不知道的东西。下面是实际查询。问题是我们有两个表,都有和EUID列。如果dbo.EU_Admin3.EUID不为NULL,则它在连接中优先。如果dbo.EU_Admin3.EUID为NULL,请改用dbo.EU_Admin2.EUID。希望澄清一下。

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3 
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END AS EUID)
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

4 个答案:

答案 0 :(得分:18)

试试这个:

CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4

as col4应该在CASE结尾处发表声明。另请注意,您也错过了END

另一个可能更简单的选择是:

IIf([table3.col3] Is Null,[table2.col3],[table3.col3])

为了澄清,MS Access不支持COALESCE。如果这将是最好的方式。

根本改变问题后编辑:

要将查询转换为SQL Server,您可以使用COALESCE(因此技术上也可以回答):

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID

顺便说一下,您的CASE声明在该字段之前缺少,。这就是为什么它不起作用。

答案 1 :(得分:1)

看起来它可能属于select语句:

SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END)
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT OUTER JOIN table3
ON table1.id = table3.id

答案 2 :(得分:1)

感谢您的帮助! @Svetoslav Tsolov非常接近,但我仍然得到一个错误,直到我发现右括号在错误的地方。这是有效的最终查询:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

答案 3 :(得分:0)

无法理解您的实际问题,但您的案例陈述不正确

CASE 
WHEN 
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END 
AS
COL4