[英]How to join result of two sql statements into one table and different columns
我有三個選擇查詢,它們根據不同的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' )
聯合會在一列中給出結果,因此它無效。 任何其他想法
只需將每個選擇語句括在括號中,為每個選擇語句指定別名,然后在頂部使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.