如何将两条sql语句的结果连接到一个表和不同的列中

如何将两条sql语句的结果连接到一个表和不同的列中,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我有三个select查询,它们根据不同的where子句从同一个表返回总记录、成功记录和失败记录。我想将所有这些语句的结果合并到一个表中,以便生成我的存储过程,但是生成的表应该有三个不同的列,分别是cdr、success和failure SELECT Count(*) AS cdr FROM ABC AS c WITH (NOLOCK) WHERE APPID IN( 1, 2 ) AND CALLDATE = '2012-10-09' SELECT Count(*)

我有三个select查询,它们根据不同的where子句从同一个表返回总记录、成功记录和失败记录。我想将所有这些语句的结果合并到一个表中,以便生成我的存储过程,但是生成的表应该有三个不同的列,分别是cdr、success和failure

SELECT Count(*) AS cdr 
FROM   ABC AS c WITH (NOLOCK) 
WHERE  APPID IN( 1, 2 ) 
       AND CALLDATE = '2012-10-09' 

SELECT Count(*) AS success 
FROM   ABC AS d WITH (NOLOCK) 
WHERE  APPID IN( 44, 45 ) 
       AND CALLDATE = '2012-10-09' 
       AND HANGUPCODE IN ( 'man', 'mach' ) 

SELECT Count(*) AS fail 
FROM   ABC WITH (NOLOCK) 
WHERE  APPID IN( 44, 45 ) 
       AND CALLDATE = '2012-10-09' 
       AND HANGUPCODE NOT IN ( 'man', 'mach' ) 

Union在一列中给出结果,因此它将不起作用。任何其他想法

只需将每个select语句用括号括起来,为每个select语句指定一个别名,并在顶部使用
select

SELECT 
  (select count(*) as cdr  
   from abc as c with (nolock) 
   where appid in(1,2)  and calldate = '2012-10-09'
  ) AS Column1,  
  (select count(*) as success  
   from abc as d with (nolock) 
   where appid in(44,45) and calldate = '2012-10-09' 
       and hangupcode in ('man', 'mach')
  ) AS Column2, 
  (select count(*) as fail  
   from abc  with (nolock) 
   where appid in(44,45) and calldate = '2012-10-09' 
       and hangupcode not in  ('man', 'mach')
  ) AS Column3

基本上,您将每个查询视为一个单独的列。

我不明白,您想要一个只有一行和三列的结果集吗?
  SELECT a.cdr, b.success, c.failure FROM 
  (SELECT count(*) AS cdr  
   FROM abc as c WITH (NOLOCK) 
   WHERE appid IN (1,2) AND
         calldate = '2012-10-09'
  ) AS a,   
  (SELECT count(*) AS success  
   FROM abc AS d WITH (NOLOCK) 
   WHERE appid IN (44,45) AND 
         calldate = '2012-10-09' AND 
         hangupcode IN ('man', 'mach')
  ) AS b,  
  (SELECT count(*) AS fail  
   FROM abc WITH (NOLOCK) 
   WHERE appid IN (44,45) AND
         calldate = '2012-10-09' AND 
         hangupcode NOT IN ('man', 'mach')
  ) AS c
select a.cdr, b.success, c.fail from
( select count(*) as cdr  
from abc as c with (nolock) where appid in(1,2)  
and calldate = '2012-10-09' ) a
, ( select count(*) as success  
from abc as d with (nolock) where appid in(44,45)  
and calldate = '2012-10-09'
and hangupcode in ('man', 'mach') ) b
, ( select count(*) as fail  from abc  with (nolock) where appid in(44,45) and calldate = '2012-10-09'and hangupcode not in  ('man', 'mach') ) c
select
   sum(case when appid in(1,2) and calldate = '2012-10-09' then 1 else 0 end) as cdr,
   sum(case when appid in(44,45) and calldate = '2012-10-09'and hangupcode in ('man', 'mach') then 1 else 0 end) as success,
   sum(case when appid in(44,45) and calldate = '2012-10-09'and hangupcode not in  ('man', 'mach') then 1 else 0 end)as fail
from abc