组合两个查询以生成一行结果

时间:2014-10-01 14:46:37

标签: sql sql-server

我有两个查询,每个查询产生按关键字段分组的记录数

查询1

select link_to_contract_header, count(*) 'total1'
from calls with (nolock)
where call_type in ('HB','PI')
group by link_to_contract_header
order by link_to_contract_header

查询2

select link_to_contract_header, count(*) 'total2'
from call_events with (nolock)
inner join calls with (nolock) on link_to_call=call_ref
where call_type in ('HB','PI')
group by link_to_contract_header
order by link_to_contract_header

查询1产生

的结果
SPSL-1      1
SPTEST-1    81
SSOLUT-1    21
TEST-1      22
WARMG-1     177

查询2生成

的结果
SPSL-1      3
SPTEST-1    301
SSOLUT-1    371
TEST-1      145
WARMG-1     4339

所以问题是......我如何组合这两个查询,以便最终得到一组结果与同一行中的2个数字? SQL 2000服务器,使用SQL Server management studio express 2005来运行查询。

SPSL-1     1   3
SPTEST-1   81  301

1 个答案:

答案 0 :(得分:4)

使用现有查询作为派生表的快速方法

SELECT 
    t1.link_to_contract_header,
    t1.total1,
    t2.total2
FROM
    (select link_to_contract_header, count(*) 'total1'
    from calls with (nolock)
    where call_type in ('HB','PI')
    group by link_to_contract_header) t1
JOIN
    (select link_to_contract_header, count(*) 'total2'
    from call_events with (nolock)
    inner join calls with (nolock) on link_to_call=call_ref
    where call_type in ('HB','PI')
    group by link_to_contract_header) t2 ON t1.link_to_contract_header = t2.link_to_contract_header