SQL Server JOIN ON value ELSE NULL



我正在处理一个需要联接数据的查询。我有一张表格,里面有各种状态信息。这些具有类似于例如"a1_1"的failureBitNr。然后我有第二个表,它将"a1_1"翻译成人类可读的文本(lng_English)。默认情况下,第二个表具有"a1_1"的翻译。但这也可以被另一个特定的翻译覆盖,例如,当failureBitNr用于标准以外的另一种状态时。

因此,我需要将状态表与failureBitNr上的转换表连接起来。这没那么难。

但是,我如何将它加入到覆盖基本翻译的翻译中呢?

表2如下所示:

id   fileProjectNr MachineNr failureBitNr  lng_English
905  2203456       2         a6_1          This message overwrites the standard
205  NULL          NULL      a6_1          Standard message for a6_1
204  NULL          NULL      a1_1          Standard message for A1_1
203  NULL          NULL      a1_2          Standard message for A1_2

请注意,覆盖现有消息的消息包含一个非NULL的fileProjectNr。所有标准消息都有一个fileProjectNr NULL

因此,仅在FailureBitNr上加入将返回两行(905和205)。但我需要在failureBitNr上加入,并在fileProjectNr不为NULL的情况下做一些事情。

所以我做了这个:

DECLARE @ProjectNr int = 123456
SELECT
    t1.*,
t2.*
FROM
    Table1 AS t1
LEFT JOIN
    Table2 AS t2
ON
(t1.failureBitNr = t2.failureBitNr)
AND
    (t2.fileProjectNr LIKE
    CASE WHEN t2.fileProjectNr = @ProjectNr THEN
        @ProjectNr
    ELSE
        NULL
    END
)
WHERE
    {where statement}

这将返回ID 905,但是,如果在failureBitNr a1_1和a1_2上也存在联接,则这些联接将全部返回为"NULL",而不是"ax_x的标准消息"。

有人知道怎么解决这个问题吗?

我的第一个想法:

SELECT     t1.*, t2.* FROM     Table1 AS t1 
    LEFT JOIN  Table2 AS t2 (t1.failureBitNr = t2.failureBitNr)
    where t2.fileProjectNr is not NULL
union all               
    SELECT     t1.*, t2.* FROM     Table1 AS t1 
    LEFT JOIN  Table2 AS t2 (t1.failureBitNr = t2.failureBitNr) and 
    where t1.failureBitNr not in (select failureBitNr from Table2 where fileProjectNr is not NULL)

不使用加入,而是先使用UNION ALL,然后使用failureBitNrGROUP BY,再使用SELECTlng_EnglishMAX(fileProjectNr)MAXfileProjectNr

最新更新