I have the following 2 example queries plus their result tables (dummy data) below:
SELECT
subs.Region
,subs.Product
,SUM(p.Price) TotalPriceA
FROM dbo.submission_dtl subs
JOIN dbo.price_dtl p ON subs.SubmissionNumber = p.SubmissionNumber
GROUP BY subs.Region, subs.Product
| Region | Product | TotalPriceA |
|---|---|---|
| USA | cameras | 200 |
| USA | phones | 300 |
| Canada | cameras | 300 |
| Canada | phones | 500 |
SELECT
r.Region
,r.Product
,SUM(rp.Price) TotalPriceB
FROM dbo.report_dtl r
JOIN dbo.report_price rp ON r.SubmissionNumber = rp.SubmissionNumber
GROUP BY r.Region, rp.Product
| Region | Product | TotalPriceB |
|---|---|---|
| USA | cameras | 201 |
| USA | phones | 301 |
| Canada | cameras | 301 |
| Canada | phones | 501 |
I want to join them so that the result table resembles this:
| Region | Product | TotalPriceA | TotalPriceB |
|---|---|---|---|
| USA | cameras | 200 | 201 |
| USA | phones | 300 | 301 |
| Canada | cameras | 300 | 301 |
| Canada | phones | 500 | 501 |
But when I used this query, I got a result table that resembled this:
SELECT
subs.Region
,subs.Product
,SUM(p.Price) TotalPriceA
,rptotal.TotalPriceB
FROM dbo.submission_dtl subs
JOIN dbo.price_dtl p ON subs.SubmissionNumber = p.SubmissionNumber
JOIN
(
SELECT
r.Product
,SUM(rp.Price) TotalPriceB
FROM dbo.report_dtl r
JOIN dbo.report_price rp ON r.SubmissionNumber = rp.SubmissionNumber
GROUP BY rp.Product
) rptotal on subs.Product = rptotal.Product
GROUP BY subs.Region, subs.Product, rptotal.TotalPriceB
| Region | Product | TotalPriceA | TotalPriceB |
|---|---|---|---|
| USA | cameras | 200 | 502 |
| USA | phones | 300 | 802 |
| Canada | cameras | 300 | 502 |
| Canada | phones | 500 | 802 |
When I group the subquery by region as well, I get even worse results…
>Solution :
You can try to use two subquery before join
SELECT t1.Region,
t1.Product,
t2.TotalPriceA,
t1.TotalPriceB
FROM (
SELECT
r.Region
,r.Product
,SUM(rp.Price) TotalPriceB
FROM dbo.report_dtl r
JOIN dbo.report_price rp ON r.SubmissionNumber = rp.SubmissionNumber
GROUP BY r.Region, rp.Product
) t1 INNER JOIN (
SELECT
subs.Region
,subs.Product
,SUM(p.Price) TotalPriceA
FROM dbo.submission_dtl subs
JOIN dbo.price_dtl p ON subs.SubmissionNumber = p.SubmissionNumber
GROUP BY subs.Region, subs.Product
) t2 ON t1.Region = t2.Region AND t1.Product = t2.Product