简体   繁体   中英

Summing columns in two tables then joining tables

I have two tables set up in the same way, but with different values. Here are samples from each:

Table1:

Date        Code       Count
1/1/2015    AA         4
1/3/2015    AA         2
1/1/2015    AB         3

Table2:

Date        Code       Count
1/1/2015    AA         1
1/2/2015    AA         0
1/4/2015    AB         2

I would like the result table to contain all unique date-code pairs, with any duplicates between the tables having the counts of the two summed.

Output_Table:

Date        Code       Count
1/1/2015    AA         5  /*Summed because found in Table1 and Table2*/
1/2/2015    AA         0
1/3/2015    AA         2
1/1/2015    AB         3
1/4/2015    AB         2

I have no primary key to connect the two tables, and the joins I have tried have either not kept all distinct date-code pairs or have created duplicates.

For reference, I am doing this inside a SAS proc sql statement.

I'm on the road at the moment so I haven't run this, but:

SELECT  date ,
        code ,
        SUM([count])
FROM    ( SELECT    *
          FROM      table1
          UNION ALL
          SELECT    *
          FROM      table2
        ) [tables]
GROUP BY date ,
        code
ORDER BY date ,
        code

Will do the trick. I'll have a crack at the join version and edit this post when I get in front of a proper computer

EDIT:

Full outer joins and COALESCE will also do it, although is marginally slower, so It may depend on what else you have going on there!

SELECT  COALESCE(#table1.date, #table2.date) ,
    COALESCE(#table1.code, #table2.code) ,
    ISNULL(#table1.COUNT, 0) + ISNULL(#table2.COUNT, 0)
FROM    #table1
    FULL OUTER JOIN #table2 ON #table2.code = #table1.code
                               AND #table2.date = #table1.date
ORDER BY COALESCE(#table1.date, #table2.date) ,
    COALESCE(#table1.code, #table2.code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM