简体   繁体   中英

A way to combine 2 seperate queries into one query and 1 table?

I want to combine 2 separate queries into one query and be able to sort them into 1 table.

This is the code I am wanting to combine

SELECT 
    t1.CompanyName as 'Customer Company Name', 
    t1.ContactName, t1.ContactTitle, t1.City, t1.Country, t1.Phone 
FROM 
    Customers t1
WHERE 
    t1.Country = 'Germany'
ORDER BY 
    t1.City;

SELECT 
    t2.CompanyName as 'Supplier Company Name', 
    t2.ContactName, t2.ContactTitle, t2.City, t2.Country, t2.Phone 
FROM 
    Suppliers t2
WHERE 
    t2.Country = 'Germany'
ORDER BY 
    t2.City;

I also need to distinguish whether or not they are a supplier or a customer in the table. Is there a way to show where the data for that row came from??

I'm hoping to get something like this

Company Name | Contact Name | Phone       | Table of Origin
-------------+--------------+-------------+-----------------
Target         Steven        111-111-1111  Customer
Factory Name   Connor        222-222-2222  Supplier

I think you just want union all :

SELECT t1.CompanyName, t1.ContactName, t1.Phone, 'Customers' as which
FROM Customers t1
WHERE t1.Country = 'Germany'
UNION ALL
SELECT t2.CompanyName, t2.ContactName, t2.Phone, 'Suppliers' as which
FROM Suppliers t2
WHERE t2.Country = 'Germany';

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