SQL查询添加计数信息

时间:2014-01-15 21:21:20

标签: sql count

我的查询工作正常:

SELECT
 b.BG_BUG_ID as Defect
FROM
 BUG b
JOIN LINK l ON b.BG_BUG_ID = l.LN_BUG_ID
JOIN TEST t ON l.LN_ENTITY_ID = t.TS_TEST_ID
WHERE
 (b.BG_STATUS = 'Open') OR
 (b.BG_STATUS LIKE '%Re%') OR
 (b.BG_STATUS LIKE '%En%') OR
 (b.BG_STATUS = 'Fixed') OR
 (b.BG_STATUS = 'New') AND
 (l.LN_ENTITY_TYPE = 'TEST')
ORDER BY b.BG_BUG_ID ASC

输出结果为:

DEFECT
------
2222
3333
4444

现在我想为每个 b.BG_BUG_ID添加一个单独的行,其中包含 t.TS_TEST_ID 的总数作为缺陷所以它应该如下所示:

DEFECT Number_of_test_ids
------ ------------------
2222    26
3333    14
4444    55

我不知道在哪里添加 SELECT COUNT(?)以产生结果?

1 个答案:

答案 0 :(得分:0)

SELECT
 b.BG_BUG_ID as Defect, count(distinct t.TS_TEST_ID) as Number_of_test_IDs
FROM
 BUG b
JOIN LINK l ON b.BG_BUG_ID = l.LN_BUG_ID
JOIN TEST t ON l.LN_ENTITY_ID = t.TS_TEST_ID
WHERE
 (b.BG_STATUS = 'Open') OR
 (b.BG_STATUS LIKE '%Re%') OR
 (b.BG_STATUS LIKE '%En%') OR
 (b.BG_STATUS = 'Fixed') OR
 (b.BG_STATUS = 'New') AND
 (l.LN_ENTITY_TYPE = 'TEST')
GROUP BY B.BG_BUG_ID
ORDER BY b.BG_BUG_ID ASC

您正在使用需要group by子句的聚合函数。

如果要计算重复的t.ts_test_Ids,则可能需要删除distinct;或者如果您知道重复项不存在,或者您实际上想要两次计算相同的ID。