繁体   English   中英

SQL Server JOIN ON值ELSE NULL

[英]SQL Server JOIN ON value ELSE NULL

我正在努力寻找需要加入数据的查询。 我有一张包含各种状态信息的表格。 它们有一个failureBitNr,例如“a1_1”。 然后我有第二个表将“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 ,然后GROUP BY通过failureBitNrSELECT lng_EnglishMAX(fileProjectNr)MAX通过fileProjectNr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM