在SQL Server中组合两个表

时间:2016-07-30 21:17:26

标签: sql-server tsql

我的数据库中有两个表

Winners表:

Count   Country
--------------------
5       Hungary
2       Ireland
1       Italy
3       Netherlands

RunnerUp表:

Count     Country
----------------------
1         Italy
3         Netherlands
2         Spain

如何将这两个表组合成如下所示:

Country     Winners    RunnerUp
--------------------------------
Hungary       5          0
Ireland       2          0
Italy         1          1
Netherlands   3          3
Spain         0          2

4 个答案:

答案 0 :(得分:1)

使用联盟

select top 1 CameraID
from violations
where DateOfViolation >= dateadd(day, -7, getdate())
group by CameraID
order by count(*) desc

答案 1 :(得分:0)

您正在寻找的构造是full outer join

SELECT          COALESCE([winners].[country], [runnerup].[country]) AS country,
                COALESCE([winners].[count], 0) AS winners, 
                COALESCE([runnerup].[count], 0) AS runnerup
FROM            [winners]
FULL OUTER JOIN [runnerup] ON [winners].[country] = [runnerup].[country]

答案 2 :(得分:0)

我会在你的select中使用case语句,使用EXISTS来查询一个国家显示的值(如果不存在则为0,如果是,则为表中的值)。

这些方面的东西:

SELECT 
    countries.Country,
    CASE 
       WHEN EXISTS(SELECT Winners.Country 
                   FROM Winners 
                   WHERE countries.Country = Winners.Country) 
          THEN (SELECT SUM(Count) 
                FROM Winners 
                WHERE countries.Country = Winners.Country) 
       ELSE 0 
    END AS Winners,
    CASE 
       WHEN EXISTS(SELECT RunnerUp.Country 
                   FROM RunnerUp 
                   WHERE countries.Country = RunnerUp.Country) 
          THEN (SELECT SUM(Count) 
                FROM RunnerUp 
                WHERE countries.Country = RunnerUp.Country) 
       ELSE 0 
    END AS RunnerUp
FROM 
    (SELECT Country FROM Winners
     UNION
     SELECT Country FROM RunnerUp) as countries

我将国家/地区名称联合起来,因此结果包含所有国家/地区是否出现在两个表格中。 case语句的SELECT部分中的THEN语句只能返回一个值,所以我使用了sum()聚合。这样,如果由于某种原因,一个国家不止一次出现在同一张桌子上,我将得到两次的总数。

答案 3 :(得分:0)

更简单 - 更重要的是 - 符合标准,而不是依赖于已经功能完备的RDBMS中不需要的无意义函数,如COALESCE()

CREATE TABLE RESULTS( COUNTRY, WINNERS, RUNNER_UP ) PRIMARY KEY( COUNTRY );

INSERT INTO RESULTS  
SELECT W.COUNTRY, W.COUNT AS WINNERS  
FROM WINNERS W  
INNER JOIN ON W.COUNTRY = R.COUNTRY  
SELECT R.COUNTRY, R.COUNT AS RUNNER_UP  
FROM RUNNERS_UP R;