【问题标题】:SQL SERVER COUNT AND JOINSQL 服务器计数和连接
【发布时间】:2012-09-08 02:35:41
【问题描述】:

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

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

测试用例

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

执行

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

执行错误

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

而且我需要知道定义了多少测试用例,执行了多少测试用例,有多少测试用例有错误,有多少没有。

我正在寻找一个可以给我这种结果的查询:

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

考虑到表结构,这可能吗?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    你的意思是这样的:

    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
    

    【讨论】:

    • 我没有考虑使用子查询,因为我需要使用 where 语句过滤记录。但是让我试试这个,我告诉你它是怎么回事。非常感谢!
    • 我也在使用 PHP 和 SQL Server - 奇怪,我知道 - 所以我需要简化查询。
    • 嗯,count(42) 有什么用?和count(*)有什么区别?
    • @hagensoft - COUNT(*)COUNT(42) 返回相同的结果。对于那些坚持SELECT从不使用*的人来说,这很平静。使用常量向我表明我考虑了所需的结果,并且不希望对特定列的非 NULL 值进行计数。选择42 仅仅是因为它是Answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多