I am trying to inner join these 2 subqueries (I think that's what it's called anyways) together where the branchName of the first query is equal to the branchName of the second query.
However, they don't seem to want to join together, and with my limited knowledge of SQL I can't seem to find a way to fix this. I tried moving the brackets around in all sorts of positions but it didn't like that either.
SELECT *
FROM
(
SELECT B.branchName, A.type, AVG (T.amount), COUNT(A.accNumber)
FROM Branch B, Account A, Transactions T
WHERE
B.branchNumber = A.branchNumber AND
A.accNumber = T.accNumber
GROUP BY B.branchName, A.type
)
INNER JOIN
(
SELECT B1.branchName, COUNT(A1.accNumber)
FROM Account A1, Branch B1
WHERE
A1.branchNumber = B1.branchNumber
GROUP BY B1.branchName
HAVING COUNT(A1.accNumber) > 5
)
ON
B.branchName = B1.branchName
A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory.
Any number of subqueries can be nested in a statement.
Rewriting Subqueries as JOINSA subquery using IN can be rewritten with the DISTINCT keyword, for example: SELECT * FROM table1 WHERE col1 IN (SELECT col1 FROM table2); can be rewritten as: SELECT DISTINCT table1.
In order to make the query work, you need to name the inner selects (sub-queries):
SELECT *
FROM
(
SELECT B.branchName, A.type, AVG (T.amount), COUNT(A.accNumber)
FROM Branch B, Account A, Transactions T
WHERE
B.branchNumber = A.branchNumber AND
A.accNumber = T.accNumber
GROUP BY B.branchName, A.type
) q1
INNER JOIN
(
SELECT B1.branchName, COUNT(A1.accNumber)
FROM Account A1, Branch B1
WHERE
A1.branchNumber = B1.branchNumber
GROUP BY B1.branchName
HAVING COUNT(A1.accNumber) > 5
) q2
ON
q1.branchName = q2.branchName
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