SQL查询:如何区分供应商/客户公司并按名称升序排列
Solution for Your Query
Got it, let's tackle this problem step by step. The key here is to union your Suppliers and Customers tables while explicitly adding a type column to distinguish between the two.
Assuming your tables are named Suppliers and Customers, and both have a CompanyName column for the company name (adjust these names if your schema is different), here's the complete query:
SELECT CompanyName, 'Supplier' AS CompanyType -- This adds the type identifier for suppliers FROM Suppliers UNION ALL SELECT CompanyName, 'Customer' AS CompanyType -- This adds the type identifier for customers FROM Customers ORDER BY CompanyName ASC;
Breakdown of what this does:
UNION ALLcombines the results from both tables without removing duplicates (useUNIONinstead if you want to eliminate any company names that exist in both tables, butUNION ALLis faster if duplicates aren't a concern).- The
AS CompanyTypeclause creates a new column where we hardcode the type ('Supplier' or 'Customer') based on which table the row comes from. ORDER BY CompanyName ASCsorts the combined results alphabetically by company name, just like you need.
If your table names or column names are different (e.g., SupplierName instead of CompanyName), just swap those out with your actual schema names and this will work perfectly.
内容的提问来源于stack exchange,提问作者Bontano
相关产品推荐
相关产品推荐

