sandraknowles
sandraknowles

Reputation: 35

How to write a sql statement using union and identifying data from table a and table b

I’m trying to write a SQL query where after I have used the union I would like to identify which data is from sales table and which data is from inventory table

Select customer 
     , calendar date 
     , sales amount 
     , location 
  From Sales 
 Union 
Select customer 
     , cal date
     , sales price 
     , distribution location 
  From inventory

Upvotes: 1

Views: 56

Answers (1)

ekochergin
ekochergin

Reputation: 4129

The classical way is to use an additional column

Select 'SALES' origin,
     , customer 
     , calendar date 
     , sales amount 
     , location 
  From Sales 
 Union 
Select 'INVENTORY'
     , customer 
     , cal date
     , sales price 
     , distribution location 
  From inventory

UPD: Just FYI, "union" clause removes all the duplicates which affects the performance, so if removing duplicates is not intended it is better to use "union all" instead

Upvotes: 4

Related Questions