Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join results "generated" from two SELECT statements with different schemas into one table

So I have the following SELECT statements:

SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4)  AS Decade
FROM Movies M, Awards A
WHERE {SOME WHERE CLAUSE}
GROUP BY Decade;

and

SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade
FROM Awards A2
WHERE {SOME WHERE CLAUSE}
GROUP BY Decade;

The first one is "generating" a table with columns (US, Decade) and the second one is "generating" another table with columns (Total, Decade). I want to join those two tables so that I get a table (US, Total, Decade). How can I do it?

like image 505
Martin Marinov Avatar asked Nov 12 '11 17:11

Martin Marinov


People also ask

How do you join two tables in SQL that has no common fields?

Using the “FROM Table1, Table2” Syntax One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.

What is a cross join SQL?

What is a CROSS JOIN in SQL? In SQL, CROSS JOINs are used to combine each row of one table with each row of another table, and return the Cartesian product of the sets of rows from the tables that are joined.


1 Answers

Put them in subqueries and do a JOIN:

SELECT a.US, a.decade, b.total FROM

  (SELECT COUNT(A.Award) AS US, SUBSTRING(CAST(M.Year as char(4)), 0 , 4)  AS Decade
  FROM Movies M, Awards A
  WHERE {SOME WHERE CLAUSE}
  GROUP BY Decade ) AS a

INNER JOIN

  (SELECT COUNT(*) AS Total, SUBSTRING(CAST(A2.Year as char(4)), 0 , 4) AS Decade
  FROM Awards A2
  WHERE {SOME WHERE CLAUSE}
  GROUP BY Decade) AS b

ON a.decade = b.decade
like image 99
knittl Avatar answered Oct 06 '22 18:10

knittl