Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two sql tables when the common column has different names but information is the same in both tables

Tags:

sql

Relatively new to SQL querying. I can successfully get results from a simple query that shows a customer number and a total dollars invoiced sorted highest dollar amount to lowest. I want to also display the customer name. The customer name, [Name], is in another table along with the customer number but the column name for customer number is different, ie. Table 1 is [Bill-to Customer No_] and Table 2 is just [No_]. How would I get the information from Table 2 to display in the same row with the customer number?

like image 742
Craig Zirnheld Avatar asked Sep 13 '13 19:09

Craig Zirnheld


People also ask

How do I join two tables with different column names?

Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).

Can we join two tables if they do not have common column name?

There are few ways to combine the two tables without a common column including Cross Join (Cartesian Product) and UNION. This is not a join but can be useful for merging tables in SQL.

Which join is based on all columns in the two tables that have the same column name?

A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the common columns in the two tables being joined. Common columns are columns that have the same name in both tables. A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT OUTER join.

Which join to use when there is nothing common in both tables?

The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION.


2 Answers

SELECT [Bill-to Customer No_], [Invoice Amount] AS amt, [Name]
FROM Table1 t1 JOIN Table2 t2
ON t1.[Bill-to Customer No_] = t2.[No_]
ORDER BY amt DESC;

I haven't grasped your column names yet, but hope you get the idea.

EDIT : (as per your new query)

SELECT [Sell-to Customer No_], [Name], SUM([Amount]) as "Total Dollars Spent" 
FROM [Table 1 - LIVE$Sales Invoice Line] a JOIN [Table 2 - LIVE$Customer] b
ON a.[Sell-to Customer No_] = b.[No_]
WHERE [Source Code] = 'RENTAL' and [Sell-to Customer No_] != 'GOLF' 
GROUP BY [Sell-to Customer No_], [Name]
ORDER BY SUM([Amount]) DESC;

You need to add [Name] to the GROUP BY clause as well. Remember you cannot SELECT a column that's not a part of GROUP BY unless it's being processed by a group function like [Amount] is being processed by SUM().

like image 157
Ravi K Thapliyal Avatar answered Sep 18 '22 11:09

Ravi K Thapliyal


SELECT 
       [bill-to Customer No_]
       ,customer_name 
FROM table1 AS a 
INNER JOIN table2 AS b on a.[bill-to Customer No_]=b.No_
like image 30
Sonam Avatar answered Sep 18 '22 11:09

Sonam