0

我正在使用 Access 2007,但遇到了一条让我感到困惑的 SQL 语句。我希望使用联合来与三列中的 SQL 语句进行比较。我打算让它看起来像这样: 小样

这两个查询非常相似。就其本身而言,每个查询都按我的预期工作。如果组合成一个查询,我只会得到 2 列而不是预期的 3 列。

**注意:我在Type栏中添加了我自己的调试*

(SELECT ManufacturingRequest.reqDate, COUNT(ManufacturingRequest.reqID) AS Resolved
FROM ManufacturingRequest 
INNER JOIN QualityAssuranceApproval ON 
  ManufacturingRequest.reqID = QualityAssuranceApproval.reqID
WHERE 
  (QualityAssuranceApproval.qualityApproval AND[mfgApproval] = True) AND
  ManufacturingRequest.reqDate IS NOT NULL
GROUP BY ManufacturingRequest.reqDate
ORDER BY ManufacturingRequest.reqDate)

UNION ALL


(SELECT ManufacturingRequest.reqDate, COUNT(ManufacturingRequest.reqID) AS Unresolved
FROM ManufacturingRequest 
INNER JOIN QualityAssuranceApproval ON 
  ManufacturingRequest.reqID = QualityAssuranceApproval.reqID
WHERE 
  (QualityAssuranceApproval.qualityApproval AND[mfgApproval] = False) OR
  ManufacturingRequest.reqDate IS NOT NULL
GROUP BY ManufacturingRequest.reqDate
ORDER BY ManufacturingRequest.reqDate)

这是我最终得到的结果集。

**注意:我只是包含了类型列,以便区分两组数据。它仅用于调试。*

结果

为了创建已解决与未解决的结果,需要进行哪些更改?感谢您提供任何帮助。

4

2 回答 2

3

这里不需要联合,需要三列,第二列和第三列的计数应该是有条件的:

SELECT ManufacturingRequest.reqDate, 
        COUNT( CASE WHEN [mfgApproval] = True THEN ManufacturingRequest.reqID ELSE null END ) AS Resolved,
        COUNT( CASE WHEN [mfgApproval] = False THEN ManufacturingRequest.reqID ELSE null END ) AS Unresolved
FROM ManufacturingRequest INNER JOIN QualityAssuranceApproval ON ManufacturingRequest.reqID = QualityAssuranceApproval.reqID
WHERE (QualityAssuranceApproval.qualityApproval AND) AND ManufacturingRequest.reqDate IS NOT NULL
GROUP BY ManufacturingRequest.reqDate
ORDER BY ManufacturingRequest.reqDate

祝你好运!

于 2013-09-10T18:35:30.397 回答
2

如果你想要三列,你应该将第三列添加到两个查询中,如下所示

(SELECT ManufacturingRequest.reqDate, COUNT(ManufacturingRequest.reqID) AS Resolved, null  AS Unresolved
FROM ManufacturingRequest INNER JOIN QualityAssuranceApproval ON ManufacturingRequest.reqID = QualityAssuranceApproval.reqID
WHERE (QualityAssuranceApproval.qualityApproval AND[mfgApproval] = True) AND ManufacturingRequest.reqDate IS NOT NULL
GROUP BY ManufacturingRequest.reqDate
ORDER BY ManufacturingRequest.reqDate)

UNION ALL


(SELECT ManufacturingRequest.reqDate, null AS Resolved, COUNT(ManufacturingRequest.reqID) AS Unresolved
FROM ManufacturingRequest INNER JOIN QualityAssuranceApproval ON ManufacturingRequest.reqID = QualityAssuranceApproval.reqID
WHERE (QualityAssuranceApproval.qualityApproval AND[mfgApproval] = False) AND ManufacturingRequest.reqDate IS NOT NULL
GROUP BY ManufacturingRequest.reqDate
ORDER BY ManufacturingRequest.reqDate)
于 2013-09-10T18:30:34.413 回答