SQL查询以计数记录数必须匹配记录总数

时间:2018-07-30 11:16:08

标签: sql sql-server tsql sql-server-2008-r2

我有2张桌子

结果大师

+------+-------------+
| QnID | Description |
+------+-------------+
|    1 | Qn1         |
|    2 | Qn2         |
|    3 | Qn3         |
|    4 | Qn4         |
|    5 | Qn5         |
+------+-------------+

结果详细信息

+----+------+--------+--------+
| ID | QnID | TCDesc | Result |
+----+------+--------+--------+
|  1 |    1 | TC1    | PASS   |
|  2 |    1 | TC2    | FAIL   |
|  3 |    1 | TC3    | PASS   |
|  4 |    2 | TC1    | PASS   |
|  5 |    3 | TC1    | PASS   |
|  6 |    3 | TC1    | PASS   |
|  7 |    3 | TC3    | PASS   |
+----+------+--------+--------+

我需要一个查询,该查询将返回以下结果:

+----+------+--------+
| ID | QnID | Result |
+----+------+--------+
|  1 |    2 | PASS   |
|  2 |    3 | PASS   |
|  3 |    4 | ERROR  |
|  4 |    5 | ERROR  |
+----+------+--------+

条件: 每个问题将具有不同数量的测试用例“ ResultDetails”,我需要选择所有测试用例都通过的问题(特定问题的条目数必须与通过相同测试用例的数目相同)或错误(ResultDetail)没有问题条目。

任何人都可以帮助我进行查询,谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用公用表表达式和条件聚合来获得所需的结果。

首先,创建并填充示例表(在您将来的问题中为我们保存此步骤):

DECLARE @ResultMaster AS TABLE
(
    QnID int, 
    Description char(3)
);

INSERT INTO @ResultMaster (QnID, Description) VALUES
(1, 'Qn1'),
(2, 'Qn2'),
(3, 'Qn3'),
(4, 'Qn4'),
(5, 'Qn5');

DECLARE @ResultDetails AS TABLE
(
    ID int, 
    QnID int, 
    TCDesc char(3),
    Result char(4)
);

INSERT INTO @ResultDetails VALUES
(1, 1, 'TC1', 'PASS'),
(2, 1, 'TC2', 'FAIL'),
(3, 1, 'TC3', 'PASS'),
(4, 2, 'TC1', 'PASS'),
(5, 3, 'TC1', 'PASS'),
(6, 3, 'TC1', 'PASS'),
(7, 3, 'TC3', 'PASS');

然后,使用公用表表达式来计算通过详细信息的数量,并使用简单的计数来获取总详细信息的数量:

WITH CTE AS
(
SELECT  M.QnId, 
        COUNT(CASE WHEN Result = 'PASS' THEN 1 END) As CountPass, 
        COUNT(Result) As CountDetails
FROM @ResultMaster As M
LEFT JOIN @ResultDetails As D ON M.QnId = D.QnId
GROUP BY M.QnId
)

然后,从该cte中选择:

SELECT  ROW_NUMBER() OVER(ORDER BY QnId) AS Id,
        QnId,
        CASE WHEN CountDetails = 0 THEN 
            'ERROR'
        ELSE
            'PASS'
        END
FROM CTE
WHERE CountPass = CountDetails

结果:

+----+------+--------+
| ID | QnID | Result |
+----+------+--------+
|  1 |    2 | PASS   |
|  2 |    3 | PASS   |
|  3 |    4 | ERROR  |
|  4 |    5 | ERROR  |
+----+------+--------+

You can see a live demo on rextester.