0

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.

Max
  • 3
  • 1

1 Answers1

1

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)
LordBaconPants
  • 1,404
  • 1
  • 19
  • 22
  • The first answer is beautiful. Stack the data with a union and smash it up with aggregation. The second one is nifty, but if your table has any size to it your spool space will be very very unhappy. – JNevill Feb 24 '15 at 22:27
  • Thank you! This solves it. I didn't think of using a union. I was fumbling around with the JOIN logic. The top answer worked perfectly for me. – Max Feb 25 '15 at 13:54