4

假设我在 SQL 中有两个表:

Table_Alpha   Table_Bravo
Id | Name     Id | Name
---+------    ---+-----
 1 | Alice     1 | Charlie
 2 | Bob       2 | Bob
 3 | Charlie   3 | Dorothy

我想将这两个表组合成一个表,避免重复并跟踪每个名称来自哪个表,如下所示:

Result
Name   | Alpha | Bravo
-------+-------+------
Alice  |   1   |   0  
Bob    |   1   |   1  
Charlie|   1   |   1  
Dorothy|   0   |   1  

我认为我想要的查询看起来像这样:

SELECT Name, 1 AS Alpha, 0 AS Bravo FROM Table_Alpha
UNION
SELECT Name, 0 AS Alpha, 1 AS Bravo FROM Table_Bravo;

但是,上述查询将为出现在两个表中的每个名称返回两行。如何编写查询,以便它为每个不同的名称返回一行?

4

2 回答 2

4

这行得通吗?

SELECT DISTINCT Name, sum(Alpha) as 'Alpha', sum(Bravo) as 'Bravo'
FROM (
    SELECT Name, 1 as Alpha, 0 as Bravo from Table_Alpha
    UNION
    SELECT Name, 0 as Alpha, 1 as Bravo from Table_Bravo
) X
GROUP BY Name
于 2013-05-08T19:57:25.897 回答
0

您可以使用 aFULL JOIN并且如果Name列没有重复项,GROUP BY则不需要:

SELECT
    COALESCE(a.Name, b.Name),
    CASE WHEN a.Name IS NOT NULL THE 1 ELSE 0 END AS Alpha,
    CASE WHEN b.Name IS NOT NULL THE 1 ELSE 0 END AS Bravo
FROM
    Table_Alpha AS a
  FULL JOIN
    Table_Bravo AS b
      ON a.Name = b.Name ; 

如果有重复:

SELECT
    COALESCE(a.Name, b.Name),
    COUNT(a.Name) AS Alpha,
    COUNT(b.Name) AS Bravo
FROM
    Table_Alpha AS a
  FULL JOIN
    Table_Bravo AS b
      ON a.Name = b.Name 
GROUP BY 
    COALESCE(a.Name, b.Name) ; 
于 2013-05-08T20:18:10.867 回答