Left Join Where the right table has Having Count = 1

喜欢而已 提交于 2019-12-12 06:39:20

问题


Table 1:

ID     Values
1      1
2      2
3      3
4      4

Table 2:

ID    Values
1     1
1     2
1     2
2     4
4     5
4     6

I need a result to be:

ID    Table 1 Values    Table 2 Values
1     1                 1
2     2                 4
3     3                         *This is blank because Table 2 doesn't have ID 3
4     4                 5
4     4                 6

Notice the Exclusion of the rows in table 2 Where the Values are duplicated ( ID 1 and Value 2). Yet the 2 rows for ID 4 because both values from Table 2 for ID 4 do not have duplicity.

So this is a left join and I want only the Value from table 2 where that Value is not duplicated AND the ID matches an ID from Table 1.


回答1:


Use a CTE over table 2, and then use that as the right side of your left join:

WITH t2 AS (
    SELECT ID, Values FROM [Table 2]
    GROUP BY ID, Values
    HAVING COUNT(*) = 1
)
SELECT t1.ID, t1.Values [Table 1 Values], t2.Values [Table 2 Values]
    FROM [Table 1] t1
    LEFT JOIN t2 ON t1.ID = t2.ID


来源:https://stackoverflow.com/questions/15420520/left-join-where-the-right-table-has-having-count-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!