简体   繁体   中英

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

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

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