我有一张如下表格
termnum dialnum carrier cic mou
8007779898 8007779898 LEVEL3 432 86,466
8886605890 8886605890 LEVEL3 5102 83,302
8779069811 8779069811 LEVEL3 432 69,955
8779069811 8779069811 LEVEL3 432 69,955
以下是我用于获取上表的查询:
select c.termnum, c.dialnum, c.carrier, c.cic, sum(c.calldur)/60
from tablec c
left join tablea a
on c.dialnum = a.NUMBER8XX
group by c.termnum, c.dialnum, c.carrier, c.cic
union
select c.termnum, c.dialnum, c.carrier, c.cic, sum(c.calldur)/60
from tablec c
left join tableb b
on c.dialnum = b.NUMBER8XX
group by c.termnum, c.dialnum, c.carrier, c.cic
Termnum和dianlnum来自特定的表格,我正在尝试根据这一点来整理我的数据。我尝试了不同的案例陈述但没有结果。 我试图获取数据,如下所示:
termnum dialnum carrier cic mou table a table b
8007779898 8007779898 LEVEL3 432 86,466 X
8886605890 8886605890 LEVEL3 5102 83,302 X
8779069811 8779069811 LEVEL3 432 69,955 X X
答案 0 :(得分:2)
使用common table expression来汇总您的聚合,然后使用case
表达式exists()
来确定哪些表格dialnum
。
;with cte as (
select c.termnum, c.dialnum ,c.carrier ,c.cic ,sum(c.calldur)/60 as mou
from tablec c
group by c.termnum, c.dialnum, c.carrier, c.cic
)
select c.*
, table_a = case when exists (select 1 from tablea a where a.NUMBER8XX = c.dialnum) then 'x' else '' end
, table_b = case when exists (select 1 from tableb b where b.NUMBER8XX = c.dialnum) then 'x' else '' end
from cte c
select c.*
, table_a = case when exists (select 1 from tablea a where a.NUMBER8XX = c.dialnum) then 'x' else '' end
, table_b = case when exists (select 1 from tableb b where b.NUMBER8XX = c.dialnum) then 'x' else '' end
from (
select c.termnum, c.dialnum ,c.carrier ,c.cic ,sum(c.calldur)/60 as mou
from tablec c
group by c.termnum, c.dialnum, c.carrier, c.cic
) c
答案 1 :(得分:0)
根本不需要case
。只需在结果中添加静态列。
select c.termnum, c.dialnum, c.carrier, c.cic, sum(c.calldur)/60, 'A' as SourceTable
from tablec c
left join tablea a
on c.dialnum = a.NUMBER8XX
group by c.termnum, c.dialnum, c.carrier, c.cic
union
select c.termnum, c.dialnum, c.carrier, c.cic, sum(c.calldur)/60, 'B' as SourceTable
from tablec c
left join tableb b
on c.dialnum = b.NUMBER8XX
group by c.termnum, c.dialnum, c.carrier, c.cic