2

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!

1
  • Could you give an example of table data and desired output? Also, which RDBMS? SQL Server? Commented Jul 25, 2013 at 17:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent Thanks! I had almost all of it in my solution, I never thought to join on both columns however.
@BobFishel This will show all managers that match between the tables, but none of those that don't. May be what you want, but not quite what you asked :)
yep I switched it to a full outer join :)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.