简体   繁体   English

分组依据 - 对不同的组应用不同的过滤器

[英]Group by - Apply different filters for different groups

Query 1 -查询 1 -

select rend, pay, count(*) from payer
where pay = '1'
group by rend, pay

Query 2 -查询 2 -

select rend, count(*) from payer
where pay = '2'
or 
(
pay = '3' AND model_code IN ( 'MGD', 'MEDI' )
)
group by rend

Combined query -组合查询 -

If I combine the queries like below, I get the correct counts for the first query because it does not have any additional filters.如果我像下面这样组合查询,我会得到第一个查询的正确计数,因为它没有任何额外的过滤器。 How do I apply the filters in the second query to the below query so they don't apply to pay_type = 1 which is used in Query 1 .如何将第二个查询中的过滤器应用于以下查询,以便它们不适用于Query 1使用的pay_type = 1 Query 1 I am basically looking to combine these two queries into a single query, so I don't have to write multiple cte's for every pay that has a where clause.我基本上希望将这两个查询组合成一个查询,因此我不必为每个具有 where 子句的pay编写多个 cte。

select rend, pay, count(*) from payer
group by rend, pay
select rend, pay, count(*)
from payer
where case when pay = '1' then 1
           when pay = '2' then 1
           when pay = '3' and model_code in ('MGD', 'MEDI') then 1 
         = 1
group by rend, pay;

How about simply doing this?简单地做这个怎么样?

select rend, max(pay), count(*) from payer
where pay in ('1', '2') or
      (pay = '3' and model_code in ( 'MGD', 'MEDI' )
      )
group by rend;

It is unclear what you want for the second column for the second query.目前还不清楚第二个查询的第二列需要什么。

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

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