Reputation: 1
here is my table Prod of monthly production report:
PruID Prod1 Prod2, ReportDate
001 12.5 32.4 1/1/1999
001 13.0 32.0 2/1/1999
...
002 45.2 32.4 1/1/2004
002 56.3 43.2 2/1/2004
...
I want to summarize Prod1 and Prod2, as well as last 12 months of Prod1 & Prod2 by PruID. I wrote 2 separate queries and they are working for each purpose:
Query 1: Summarize prod1 & prod2 by PruID
SELECT Prod.PruID, Sum(Prod.Prod1) AS CumProd1, Sum(Prod.Prod2) AS CumProd2
FROM Prod
GROUP BY Prod.PruID;
Query 2: Summarize last 12 month of Prod1 & Prod2 by PruID
SELECT PruID, Sum(Prod1) AS Cum12MonProd1, Sum(Prod2) AS Cum12MonProd2
FROM Prod
WHERE Prod.ReportDate > DATEADD('m', -12, now())
GROUP BY PruID;
How to combine the 2 queries to one to produce something like this:
PruID CumProd1 CumProd2 Cum12MonProd1 Cum12MonProd2
Upvotes: 0
Views: 97
Reputation: 152596
You could either JOIN
the two subqueries:
SELECT a.PurID, a.CumProd1, a.CumProd2, b.Cum12MonProd1, b.Cum12MonProd2
FROM
(
SELECT Prod.PruID, Sum(Prod.Prod1) AS CumProd1, Sum(Prod.Prod2) AS CumProd2
FROM Prod
GROUP BY Prod.PruID
) a INNER JOIN
(
SELECT PruID, Sum(Prod1) AS Cum12MonProd1, Sum(Prod2) AS Cum12MonProd2
FROM Prod
WHERE Prod.ReportDate > DATEADD('m', -12, now())
GROUP BY PruID
) b
ON a.PruID = b.PruID;
or use a CASE
in the second set of sums:
SELECT
Prod.PruID,
Sum(Prod.Prod1) AS CumProd1,
Sum(Prod.Prod2) AS CumProd2,
Sum(CASE WHEN Prod.ReportDate > DATEADD('m', -12, now()) THEN Prod1 ELSE 0) AS Cum12MonProd1,
Sum(CASE WHEN Prod.ReportDate > DATEADD('m', -12, now()) THEN Prod2 ELSE 0) AS Cum12MonProd2
FROM Prod
GROUP BY Prod.PruID;
Upvotes: 0
Reputation: 17429
The trick here is to exclude the data that you're filtering out in the second query from the sum
function for the filtered total.
SELECT prod.pruid,
SUM (prod.prod1) AS cumprod1,
SUM (prod.prod2) AS cumprod2,
SUM (
CASE
WHEN prod.reportdate > dateadd ('m', -12, now ()) THEN
prod.prod1
ELSE
NULL
END)
AS cum12monprod1,
SUM (
CASE
WHEN prod.reportdate > dateadd ('m', -12, now ()) THEN
prod.prod2
ELSE
NULL
END)
AS cum12monprod2
FROM prod
GROUP BY prod.pruid;
Upvotes: 1