0

I have two SQL queries, this is the first one:

SELECT Activity, SUM(Amount) AS "Total Amount 2009"
FROM Activities, Incomes
WHERE Activities.UnitName = ? 
  AND Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;

Second query:

SELECT Activity, SUM(Amount) AS "Total Amount 2008"
FROM Activities, Incomes2008
WHERE Activities.UnitName = ? 
  AND Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;

How to join these two SQL queries?

3
  • 1
    Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was replaced with the proper ANSI JOIN syntax in the ANSI-92 SQL Standard (almost 30 years ago) and its use is discouraged Commented Dec 30, 2021 at 6:23
  • JOIN? Show us some sample result from each query, and also the desired combined result. Commented Dec 30, 2021 at 9:24
  • Why do you have different income tables for each year? With one, common income table you wouldn't have this problem. Commented Dec 30, 2021 at 9:28

2 Answers 2

2

I think it will help you. If your RDBMS Oracle DB use NVL instead of ISNULL. Use FULL JOIN Because if you have Activity in one Query and this Activity not exist in other you can lost this Activity. '''SQL

SELECT 
 ISNULL(T1.Activity,T2.Activity) AS Activity
,ISNULL(TotalAmount2009,0) AS TotalAmount2009
,ISNULL(TotalAmount2008,0) AS TotalAmount2008
FROM
(select Activity, SUM(Amount) as "TotalAmount2009"
from Activities, Incomes
where Activities.UnitName = ? AND
  Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity) T1
FULL JOIN 
(select Activity, SUM(Amount) as "TotalAmount2008"
from Activities, Incomes2008
where Activities.UnitName = ? AND
  Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity) T2 
ON T1.Activity=T2.Activity

'''

Sign up to request clarification or add additional context in comments.

1 Comment

Tip of today: COALESCE() - the ANSI/ISO way do to NVL, ISNULL etc.
0

use the below query to join two queries.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.