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?
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).
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.
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.
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.
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()
.
SELECT
[bill-to Customer No_]
,customer_name
FROM table1 AS a
INNER JOIN table2 AS b on a.[bill-to Customer No_]=b.No_
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With