Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INNER JOINing 2 Subqueries

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
like image 813
user4914034 Avatar asked Nov 09 '15 06:11

user4914034


People also ask

Can we use subquery in inner JOIN?

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.

Can you use 2 subqueries in a SQL query?

Any number of subqueries can be nested in a statement.

How do you write a subquery in joins?

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.


1 Answers

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
like image 189
Amit Avatar answered Sep 21 '22 19:09

Amit