简体   繁体   English

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

[英]Combine multiple queries into one query

I am trying to group by clientid and m.id . 我正在尝试按clientidm.id How can I convert these 2 queries into 1 query? 如何将这2个查询转换为1个查询?

Query 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 

Query 2 查询2

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

Update 更新

More specifically, I am looking to write this query without using a temp table. 更具体地说,我希望在不使用临时表的情况下编写此查询。

You could group only by clientid 您只能按clientid分组

And since no fields from activity_table are selected, an EXISTS can be used instead. 并且由于没有选择来自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

Why wouldn't you just write this as: 你为什么不这样写:

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;

I can't figure out what the logic should really be, but this seems like the simplest way to combine the queries. 我无法弄清楚逻辑究竟应该是什么,但这似乎是组合查询的最简单方法。

I would speculate that you simply want this query: 我推测您只需要此查询:

      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;

That is, remove m.id from the group by . 也就是说,通过将该m.idgroup by删除。 And this can in turn be simplified to: 而这又可以简化为:

      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;

Assuming that m.id is unique and non- NULL , this can be further simplified to: 假设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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM