将多个查询合并为一个查询

时间:2018-11-30 23:13:38

标签: sql sql-server

我正在尝试按clientidm.id分组。如何将这2个查询转换为1个查询?

查询1

select cs.clientid, count(distinct(m.id)) as cp
into #temp
from call_table cs 
join mem_table m 
on cs.CLIENTID = m.clientid
join activity_table a 
on a.memid = m.id 
where a.activity = 'abc'
group by cs.clientid, m.id 

查询2

select clientid, sum(cp) from #temp
group by ClientId

更新

更具体地说,我希望在不使用临时表的情况下编写此查询。

2 个答案:

答案 0 :(得分:1)

您只能按客户ID分组

并且由于没有选择来自activity_table的字段,因此可以使用EXISTS代替。

select cs.clientid, count(distinct m.id) as cp
from call_table cs 
join mem_table m on m.clientid = cs.clientid
where exists 
(
    select 1
    from activity_table a 
    where a.memid = m.id 
      and a.activity = 'abc'
)
group by cs.clientid

答案 1 :(得分:0)

为什么不这样写:

with temp as (
      select cs.clientid, count(distinct m.id) as cp
      from call_table cs join
           mem_table m 
           on cs.CLIENTID = m.clientid join
           activity_table a 
           on a.memid = m.id 
      where a.activity = 'abc'
      group by cs.clientid, m.id 
     )
select clientid, sum(cp)
from temp
group by ClientId;

我不知道逻辑应该是什么,但这似乎是组合查询的最简单方法。

我推测您只是想要此查询:

      select cs.clientid, count(distinct m.id) as cp
      from call_table cs join
           mem_table m 
           on cs.CLIENTID = m.clientid join
           activity_table a 
           on a.memid = m.id 
      where a.activity = 'abc'
      group by cs.clientid;

也就是说,从m.id中删除group by。而这又可以简化为:

      select m.clientid, count(distinct m.id) as cp
      from mem_table m join
           activity_table a 
           on a.memid = m.id 
      where a.activity = 'abc'
      group by cs.clientid;

假设m.id是唯一的而非非NULL,则可以进一步简化为:

      select m.clientid, count(*) as cp
      from mem_table m join
           activity_table a 
           on a.memid = m.id 
      where a.activity = 'abc'
      group by cs.clientid;