patternsqlMinor
Combine results of two queries, where the second relies on the first
Viewed 0 times
thecombinequerieswherereliestwofirstsecondresults
Problem
I have one query which is returning
And another query which is returning the same thing
The second query usually is returning more rows, but I only need the rows where the
Example:
Query 1 returns:
Query 2 returns:
The expected output:
QUERY 1:
QUERY 2:
name(text), total, created_atAnd another query which is returning the same thing
name(text), total, created_atThe second query usually is returning more rows, but I only need the rows where the
query1.created_at = query2.created_atExample:
Query 1 returns:
test, 10, 2015-03-06
test, 12, 2015-03-07Query 2 returns:
newtest, 14, 2015-03-05
newtest, 15, 2015-03-06
newtest, 9, 2015-03-07The expected output:
test, 10, 2015-03-06
test, 12, 2015-03-07
newtest, 15, 2015-03-06
newtest, 9, 2015-03-07QUERY 1:
SELECT
co.name
sum(c.total)
c.created_at
FROM c_report c
INNER JOIN contact co on co.id = c.contact_id
GROUP BY co.name, c.created_atQUERY 2:
SELECT
po.name
sum(p.total)
p.created_at
FROM p_report p
INNER JOIN person po on po.id = p.person_id
GROUP BY po.name, p.created_atSolution
I would use a CTE for the first query and reuse it for the second query:
Be sure to use
WITH cte AS (
SELECT co.name, sum(c.total) AS total, c.created_at
FROM c_report c
JOIN contact co ON co.id = c.contact_id
GROUP BY co.name, c.created_at
)
SELECT * FROM cte
UNION ALL
SELECT po.name, sum(p.total), p.created_at
FROM p_report p
JOIN person po ON po.id = p.person_id
WHERE EXISTS (SELECT 1 FROM cte WHERE created_at = p.created_at)
GROUP BY po.name, p.created_at;Be sure to use
UNION ALL, not UNION. You don't want to remove duplicates, and it's faster that way.Code Snippets
WITH cte AS (
SELECT co.name, sum(c.total) AS total, c.created_at
FROM c_report c
JOIN contact co ON co.id = c.contact_id
GROUP BY co.name, c.created_at
)
SELECT * FROM cte
UNION ALL
SELECT po.name, sum(p.total), p.created_at
FROM p_report p
JOIN person po ON po.id = p.person_id
WHERE EXISTS (SELECT 1 FROM cte WHERE created_at = p.created_at)
GROUP BY po.name, p.created_at;Context
StackExchange Database Administrators Q#94661, answer score: 4
Revisions (0)
No revisions yet.