这是我的月产量报告表:
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
...
我想总结一下Prod1和Prod2,以及过去12个月的Prod1& Pru2的Prod2。我写了两个单独的查询,他们正在为每个目的工作:
查询1:总结prod1& pru2 prod2
SELECT Prod.PruID, Sum(Prod.Prod1) AS CumProd1, Sum(Prod.Prod2) AS CumProd2
FROM Prod
GROUP BY Prod.PruID;
查询2:总结过去12个月的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;
如何将2个查询组合成一个以生成如下内容:
PruID CumProd1 CumProd2 Cum12MonProd1 Cum12MonProd2
答案 0 :(得分:1)
此处的诀窍是从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;
答案 1 :(得分:0)
您可以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;
或在第二组总和中使用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;