[英]Sum the same column different ways
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. 我想总结一下Prod1和Prod2,以及PruID的Prod1和Prod2的最后12个月。 I wrote 2 separate queries and they are working for each purpose: 我编写了2个独立的查询,它们针对每种目的而工作:
Query 1: Summarize prod1 & prod2 by PruID 查询1:通过PruID汇总prod1和prod2
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 查询2:通过PruID汇总Prod1和Prod2的最后12个月
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
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. 这里的技巧是将第二个查询中要筛选出的数据从sum
函数中排除以筛选出的总数。
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;
You could either JOIN
the two subqueries: 您可以JOIN
两个子查询:
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: 或在第二组总和中使用CASE
:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.