SQL JOIN与COALESCE条件是重复行

时间:2016-01-25 02:33:35

标签: sql-server join duplicates left-join coalesce

我正在尝试将两张桌子连在一起。第一个表包含我不想复制的数据记录。第二个表我正在加入第一个表,用不同的[profileId]和[role]查找[value]。第二个表中的[profileId],[role]列对组合有唯一约束,但[role]有时可能为NULL,在这种情况下,我将该值视为该配置文件的默认值。

如何在不重复行的情况下将这些表连接在一起,而不使用多个左连接?我的实际查询比示例更复杂。

见下面的例子。

DECLARE @temp TABLE ([profileId] int, [role] int)
DECLARE @temp2 TABLE ([profileId] int, [role] int, [value] nvarchar(50))

INSERT INTO @temp ([profileId], [role]) VALUES (1, 1)
INSERT INTO @temp ([profileId], [role]) VALUES (1, 2)
INSERT INTO @temp ([profileId], [role]) VALUES (2, 1)
INSERT INTO @temp ([profileId], [role]) VALUES (2, 2)
INSERT INTO @temp2 ([profileId], [role], [value]) VALUES (1, 1, 'MATCH')
INSERT INTO @temp2 ([profileId], [role], [value]) VALUES (1, NULL, 'DEFAULT1')
INSERT INTO @temp2 ([profileId], [role], [value]) VALUES (2, NULL, 'DEFAULT2')

SELECT
    T1.[profileId],
    T1.[role],
    T2.value
FROM
    @temp T1
    JOIN @temp2 T2 ON T1.profileId = T2.profileId AND COALESCE(T2.[role], T1.[role]) = T1.[role]

这给了我(我理解为什么)

================================
| profileId | role  |  value   |
================================
|     1     |   1   |  MATCH   |
--------------------------------
|     1     |   1   | DEFAULT1 |
--------------------------------
|     1     |   2   | DEFAULT1 |
--------------------------------
|     2     |   1   | DEFAULT2 |
--------------------------------
|     2     |   2   | DEFAULT2 |
================================

虽然我想要

================================
| profileId | role  |  value   |
================================
|     1     |   1   |  MATCH   |
--------------------------------
|     1     |   2   | DEFAULT1 |
--------------------------------
|     2     |   1   | DEFAULT2 |
--------------------------------
|     2     |   2   | DEFAULT2 |
================================

3 个答案:

答案 0 :(得分:3)

这个SQL工作正常:

findViewById()

答案 1 :(得分:1)

您可以使用APPLYTOP

SELECT
    t.profileId,
    t.role,
    x.value
FROM @temp t
OUTER APPLY(
    SELECT TOP 1 value
    FROM @temp2
    WHERE
        profileId = t.profileId
        AND (role = t.role OR role IS NULL)
    ORDER BY 
        CASE WHEN role IS NOT NULL THEN 0 ELSE 1 END
)x

答案 2 :(得分:0)

如果您知道DEFAULT值使用left join

<强> SQL Fiddle Demo

SELECT
    T1.[role],
    COALESCE(T2.value, 'DEFAULT') as value
FROM
    temp T1
LEFT JOIN temp2 T2 
       ON T1.[role] = T2.[role]; 

否则

SELECT
    T1.[role],
    COALESCE(T2.value, (SELECT value 
                        FROM temp2 
                        WHERE role is NULL and temp2.profileID = T1.profileID)) as value
FROM
    temp T1
LEFT JOIN temp2 T2 
       ON T1.[role] = T2.[role]
      AND T1.[profileID] = T2.[profileID]
       ;