SQL SERVER COUNT AND JOIN

时间:2012-09-08 02:35:42

标签: php sql sql-server-2008 join pivot

大家好我在sql server中进行查询时遇到问题。

我有3个表:testcases,executions和execution_bugs:

测试用例

id | name
-------------
1  | Login
2  | Logout

执行

id | testcase_id
-----------------
1  | 1
2  | 2
3  | 1

execution_bugs

execution_id | bug_id
----------------------
1            | B-1
3            | B-2

我需要知道有多少个测试用例被定义,有多少个测试用例被执行,有多少个测试用例有bug,有多少没有。

我正在寻找能给我这种结果的查询:

testcases_n | executed | with_bugs | without_bugs | bugs_amount
---------------------------------------------------------------
2           | 2        | 1         | 1            | 2

这是否可以根据表结构进行?

谢谢!

1 个答案:

答案 0 :(得分:0)

你的意思是这样的:

declare @testcases as table ( id int, name varchar(16) )
insert into @testcases ( id, name ) values
  ( 1, 'login' ), ( 2, 'Logout' )

declare @executions as table ( id int, testcase_id int )
insert into @executions ( id, testcase_id ) values
  ( 1, 1 ), ( 2, 2 ), ( 3, 1 )

declare @execution_bugs as table ( execution_id int, bug_id varchar(16) )
insert into @execution_bugs ( execution_id, bug_id ) values
  ( 1, 'B-1' ), ( 3, 'B-2' )

select
  ( select count(42) from @testcases ) as testcases_n,
  ( select count(distinct testcase_id) from @executions ) as executed,
  ( select count(distinct e.testcase_id) from @executions as e inner join @execution_bugs as eb on eb.execution_id = e.id ) as with_bugs,
  ( select count(42) from @testcases ) - ( select count(distinct e.testcase_id) from @executions as e inner join @execution_bugs as eb on eb.execution_id = e.id ) as without_bugs,
  ( select count(42) from @execution_bugs ) as bugs_amount