简体   繁体   中英

SQL Select distinct values from multiple tables

So here's my setup I have 2 tables Old and New with the following (simplified) schemas

Old
[ManName]
[ManNumber]

New
[Manager_Name]
[Manager_Number]

I'm looking to craft a SQL query that returns the following but in 4 columns in 1 query as opposed to 2 queries with 2 columns each

select distinct manname, mannumber from OLD 
select distinct Manager_Name, Manager_Number from NEW

So my ideal Result Set would have 4 columns:

ManName ManNumber Manager_Name Manager Number 

Thanks!

have you tried a JOIN statement:

select distinct * 
from old a join new b on a.ManName = b. Manager_Name and a. ManNumber = b. Manager_Number

Using pretty much any RDBMS except MySQL, you can do it with CTEs and ROW_NUMBER() ;

WITH cteOld AS (
  SELECT DISTINCT ManName, ManNumber, 
         ROW_NUMBER() OVER (ORDER BY ManNumber) rn FROM Old
), cteNew AS (
  SELECT DISTINCT Manager_Name, Manager_Number,
         ROW_NUMBER() OVER (ORDER BY Manager_Number) rn FROM New
)
SELECT ManName, ManNumber, Manager_Name, Manager_Number 
FROM cteOld
FULL OUTER JOIN cteNew
  ON cteOld.rn=cteNew.rn

An SQLfiddle to test with .

Another, easier, way to just get all of them is to simply use a UNION;

SELECT ManName, ManNumber, 0 isNew FROM Old
UNION 
SELECT Manager_Name, Manager_Number, 1 FROM New

Another SQLfiddle .

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