My Problem is the following: Say you have three different tables (Products, Bills and Returns)
| ProductId | Name |
=====================
| 1 | Car |
| BillId | ProductId | Amount |
=================================
| 1 | 1 | 100$ |
| 2 | 1 | 200$ |
| ReturnId | ProductId | Amount |
===================================
| 1 | 1 | 50$ |
How would a SINGLE Query look like to get the following output:
| Product-ID | Name | Type | Amount |
=====================================
| 1 | Car | Bill | 100$ |
| 1 | Car | Bill | 200$ |
| 1 | Car | Ret | 50$ |
I was trying with all sorts of Joins, and somehow I can't get my head around this. What am I doing wrong? The closest solution I have found till now was something like this:
SELECT p.*,
(CASE
WHEN b.Amount IS NOT NULL THEN 'Bill'
ELSE 'Ret'
END) AS Type,
COALESCE(b.Amount, r.Amount) AS Amount
FROM Products p
LEFT JOIN Bills b ON b.ProductId = p.ProductId
LEFT JOIN Returns r ON r.ProductId = p.ProductId
One thing is very important to me: The real scenario-query is MUCH bigger, and I don't want to copy/paste the whole logic of there query as if it would be the case when using a Union.
Multiple joins can be described as a query containing joins of the same or different types used more than once, thus giving them the ability to combine multiple tables.
In fact, you can join as many tables as you like – the idea behind it is the same as joining only two tables. It's very helpful to take a look at the data midstep and imagine that the tables you've already joined are one table.
In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.
Yes, you can! 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. The latter is technically not a join but can be handy for merging tables in SQL.
The below would work as needed,
SELECT Products.*,
[Type],
Amount
FROM Products
INNER JOIN
( SELECT ProductID, 'Bill' [Type], Amount
FROM Bills
UNION ALL
SELECT ProductID, 'Ret' [Type], Amount
FROM Returns
) transactions
ON transactions.ProductID = Products.ProductID
You can use UNION
:
SELECT p.*, 'Bill' as [Type], b.Amount
FROM Products p
INNER JOIN Bills b
ON b.ProductId = p.ProductId
UNION
SELECT p.*, 'Ret' as [Type], r.Amount
FROM Products p
INNER JOIN Returns r
ON r.ProductId = p.ProductId
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