我有一个用户想要报告中的汇总数据。我可以使用两个单独的SQL查询来获取正确的数据,它们如下。
SELECT JH.ProjectID, SUM(EstProdHours) AS EstProdHrs, SUM(ActProdHours)
AS ActProdHrs
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> ''
GROUP BY JH.ProjectID ORDER BY JH.ProjectID
SELECT JH.ProjectID, SUM(EstProdHours) + SUM(EstSetHours) AS Earned
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> '' AND OpComplete = 1
GROUP BY JH.ProjectID ORDER BY JH.ProjectID
这两个单独的查询自行提供正确的数据。但是,我的目标是使用这两个查询的结果以及如下所示的结果来设置一个SQL视图:
ProjectID EstProdHrs ActProdHrs Earned
6000 480.00 1640.59 477
6001 621.00 2431.04 619
6002 6687.97 23234.23 6695.47
6003 414.97 4731.47 416.72
6004 208.00 2196.52 206.00
6005 2.00 76.77 NULL <--- This would show up if no completed ops in 2nd select statement
6006 20.83 819.29 18.83
我试图内部连接这两个查询,但我似乎无法避免出现“语法错误”。这是该语句:
SELECT * FROM
(SELECT JH.ProjectID, SUM(EstProdHours) AS EstProdHrs, SUM(ActProdHours) AS
ActProdHrs,'N/A' AS ValueMissingTableB
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> ''
) AS 1
INNER JOIN
(SELECT JH2.ProjectID, SUM(EstProdHours) + SUM(EstSetHours) AS Earned
FROM JobOper AS JO2 INNER JOIN JobHead AS JH2 ON JO2.Company = JH2.Company
AND JO2.JobNum = JH2.JobNum WHERE JH2.ProjectID <> '' AND OpComplete = 1
) AS 2
ON 1.ProjectID = 2.ProjectID
我也尝试了UNION和UNION ALL,但失败了,因为两个查询没有相同数量的记录。我希望我在这里犯了一个菜鸟错误,可以做到这一点。感谢您的任何见识。
答案 0 :(得分:1)
尝试一下:
WITH A AS (SELECT JH.ProjectID, SUM(EstProdHours) AS EstProdHrs, SUM(ActProdHours) AS
ActProdHrs,'N/A' AS ValueMissingTableB
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> ''
GROUP BY JH.ProjectID ORDER BY JH.ProjectID
),
B AS
(SELECT JH2.ProjectID, SUM(EstProdHours) + SUM(EstSetHours) AS Earned
FROM JobOper AS JO2 INNER JOIN JobHead AS JH2 ON JO2.Company = JH2.Company
AND JO2.JobNum = JH2.JobNum WHERE JH2.ProjectID <> '' AND OpComplete = 1
GROUP BY JH2.ProjectID ORDER BY JH2.ProjectID
)
SELECT * FROM A
JOIN B ON A.ProjectID = B.ProjectID
答案 1 :(得分:0)
我没有您的表可以对此进行测试,但是您不能直接进行左联接;
SELECT A.ProjectID,A.EstProdHrs, A.ActProdHrs, E.Earned
FROM (
SELECT JH.ProjectID, SUM(EstProdHours) AS EstProdHrs, SUM(ActProdHours) AS ActProdHrs
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> ''
GROUP BY JH.ProjectID
) A
LEFT JOIN (
SELECT JH.ProjectID, SUM(EstProdHours) + SUM(EstSetHours) AS Earned
FROM JobOper AS JO INNER JOIN JobHead AS JH ON JO.Company = JH.Company AND
JO.JobNum = JH.JobNum WHERE JH.ProjectID <> '' AND OpComplete = 1
GROUP BY JH.ProjectID
) E
ON A.ProjectID=E.ProjectID
ORDER BY A.ProjectID