Join two sql queries Join two sql queries database database

Join two sql queries


Some DBMSs support the FROM (SELECT ...) AS alias_name syntax.

Think of your two original queries as temporary tables. You can query them like so:

SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008"FROM (query1) as t1, (query2) as t2WHERE t1.Activity = t2.Activity


SELECT Activity, arat.Amount "Total Amount 2008", abull.Amount AS "Total Amount 2009"FROM  Activities aLEFT OUTER JOIN  (  SELECT ActivityId, SUM(Amount) AS Amount  FROM Incomes ibull  GROUP BY    ibull.ActivityId  ) abullON abull.ActivityId = a.ActivityIDLEFT OUTER JOIN  (  SELECT ActivityId, SUM(Amount) AS Amount  FROM Incomes2008 irat  GROUP BY    irat.ActivityId  ) aratON arat.ActivityId = a.ActivityIDWHERE a.UnitName = ?ORDER BY Activity


I would just use a Union

In your second query add the extra column name and add a '' in all the corresponding locations in the other queries

Example

//reverse order to get the column namesselect top 10 personId, '' from Telephone//No Column name assigned Union select top 10 personId, loanId from loan