多个自我加入

时间:2019-08-19 12:32:25

标签: sql-server tsql

我正在处理一个名为ERRMSG的表。错误有4种语言(有一个名为LANGU的列,其值是L1,L2,L3,L4)。 MSGKEY是应用程序名称,MSGNUM是其ID。如果您选择一种语言,则MSGKEY和MSGNUM一起是唯一的。我将对它们进行翻译,因此我将创建一个翻译表,其中每个翻译都将放在一行中。我的查询正在重复:

SELECT  X.MSGKEY, X.MSGNUM,
    ISNULL((L1.MESSAGE),'') AS L1TEXT,
    ISNULL((L2.MESSAGE),'') AS L2TEXT,
    ISNULL((L3.MESSAGE),'') AS L3TEXT,
    ISNULL((L4.MESSAGE),'') AS L4TEXT
FROM ERRMSG X
FULL JOIN ERRMSG L1 ON (X.MSGKEY = L1.MSGKEY AND X.MSGNUM = L1.MSGNUM AND L1.LANGU = 'L1')
FULL JOIN ERRMSG L2 ON (X.MSGKEY = L2.MSGKEY AND X.MSGNUM = L2.MSGNUM AND L2.LANGU = 'L2')
FULL JOIN ERRMSG L3 ON (X.MSGKEY = L3.MSGKEY AND X.MSGNUM = L3.MSGNUM AND L3.LANGU = 'L3')
FULL JOIN ERRMSG L4 ON (X.MSGKEY = L4.MSGKEY AND X.MSGNUM = L4.MSGNUM AND L4.LANGU = 'L4')

我做错了什么?我猜测联接类型可能会解决它,但不知道如何解决。

1 个答案:

答案 0 :(得分:1)

我认为可以使用条件聚合来解决:

SELECT  MSGKEY, 
        MSGNUM,
        MAX(CASE WHEN LANGU = 'L1' THEN MESSAGE END) AS L1TEXT,
        MAX(CASE WHEN LANGU = 'L2' THEN MESSAGE END) AS L2TEXT,
        MAX(CASE WHEN LANGU = 'L3' THEN MESSAGE END) AS L3TEXT,
        MAX(CASE WHEN LANGU = 'L4' THEN MESSAGE END) AS L4TEXT
FROM ERRMSG 
GROUP BY MSGKEY, MSGNUM