Search code examples
sqlsql-serverjoinsql-server-2014

SQL Server: add values of small tables to the values of big table without losing the dimensions of the big table?


I have 3 tables. I want to add corresponding values from second table and third table to the first table in the picture below. Each table has an ID by which they can be matched, ... field in the pictures. The first table has 1531 rows with an ID column and 8 other columns. This table, the top table in the pictures, is almost full of zeroes.

I have tried to join the tables in different ways but the problem is that each table has different number of rows and hence different number unique IDs. The top table has all IDs.

Is there some convenient way to add the second table to the first table and then the third table to that result?

enter image description here

Result of Left Join as suggested Suzena: why do the numbers not get summed up together?

enter image description here


Solution

  • Method1: Joins

    select a.id,(a.col1 + b.col1+c.col1) as col1, (a.col2 + b.col2 + c.col2) as col2, (a.col3 + b.col3 + c.col3) as col3
    from
    table1 a
    left join
    table2 b
    on a.id = b.id
    left join
    table3 c
    on a.id = c.id;    
    

    Method2: Unions

    select id,sum(col1) col1, sum(col2) col2, sum(col3) col3
    from
    (
        select id,col1,col2,col3
        from table1
        union all
        select id,col1,col2,col3
        from table2  
        union all  
        select id,col1,col2,col3
        from table3
    ) t
    group by id
    

    Let me know if you have any different criteria.

    Method 3: having different number of fields so use NULL or 0

    SELECT
        [MID],
        SUM([KEVAT 201501-04]) AS      'KEVAT 201501-04',
        SUM([KESA 201504-06]) AS       'KESA 201504-06',
        SUM([SYKSY 201507-09]) AS      'SYKSY 201507-09',
        SUM([TALVI 201510-12]) AS      'TALVI 201510-12',
        SUM([KEVAT 201601-04]) AS      'KEVAT 201601-04',
        SUM([KESA 201604-06]) AS       'KESA 201604-06',
        SUM([SYKSY 201607-09]) AS      'SYKSY 201607-09',
        SUM([TALVI 201610-12]) AS      'TALVI 201610-12'
    FROM
    (
    
    SELECT * FROM TABLE1
    
    UNION ALL
    
    SELECT [MID]
            ,0 AS 'KEVAT 201501-04'
            ,0 AS 'KESA 201504-06'
            ,0 AS 'SYKSY 201507-09'
            ,0 AS 'TALVI 201510-12'
            ,[KEVAT 201601-04]
            ,[KESA 201604-06]
            ,[SYKSY 201607-09]
            ,[TALVI 201610-12]
    FROM TABLE2
    
    UNION ALL
    
    SELECT [MID]
            ,[KEVAT 201501-04]
            ,[KESA 201504-06]
            ,[SYKSY 201507-09]
            ,[TALVI 201510-12]
            ,0 AS 'KEVAT 201601-04'
            ,0 AS 'KESA 201604-06'
            ,0 AS 'SYKSY 201607-09'
            ,0 AS 'TALVI 201610-12'
      FROM TABLE3
    ) a
    GROUP BY [MID]