Search code examples
sql-serverssms-18

Combine 2 tables into 1 query


I have problem to combining 2 queries into 1 using WITH statement and JOIN. I've tried that but non of it makes the output the way I wanted.

Desired Output

the wanted output ?

The Separate Outputs

nominal A

nominal B

JOIN results

combine using JOIN


Solution

  • WITH your_first_query AS (
      SELECT ...
    )
    , your_second_query AS (
      SELECT ...
    )
    SELECT your_first_query.OFFICE
         , your_first_query.MONTH
         , your_first_query.NOMINAL_A
         , your_second_query.NOMINAL_B
    FROM   your_first_query
     INNER
      JOIN your_second_query
        ON your_second_query.OFFICE = your_first_query.OFFICE
       AND your_second_query.MONTH = your_first_query.MONTH
    ORDER
        BY your_first_query.OFFICE
         , your_first_query.MONTH
    ;