仅在 PostgreSQL 中使用具有选定值的过滤器对列值求和
Sum column values using filter with selected values only in PostgreSQL
我有一个数据集:
Code | Value0 | Value1 | Value2 |
------------| --------|----------- | -----------|
CAR | 44000 | 5.0 | 2 |
CBB | 1000 | 0.89 | 9 |
CC | 1450 | 1.56 | 5 |
CIVG | 21000 | 0.786 | 19 |
CIVR | 7000 | 134.6 | 15 |
CBB | 21000 | 440 | 39 |
CC | 14000 | 16.78 | 35 |
CIVG | 100 | 98.56 | 9 |
CIVR | 45000 | 15 | 54 |
我想基于列 code
进行聚合,使用过滤器 Only those rows should be summed which have value0 greater than 10000
。但是,此例外或过滤器应仅适用于代码 CIVG and CIVR
。此过滤器将不适用于其他代码。
我已经弄清楚的查询:
select code ,
count(1) filter (where value0 > 10000 ) as funt,
count(1) ount,
sum(value2) filter (where value0 > 10000 ) "farc" ,
sum(value2) "oarc"
from table
group by code
order by code;
使用它,我得到以下结果:
Code | funt | ount | farc | oarc |
------------| -----|---------| ------------|----------|
CAR | 1 | 1 | 2 | 2 |
CBB | 1 | 2 | 39 | 48 |
CC | 1 | 2 | 35 | 40 |
CIVG | 1 | 2 | 19 | 28 |
CIVR | 1 | 2 | 54 | 69 |
我想要的是除了 CIVG
和 CIVR
之外的变量不应该对它们应用过滤器,这会产生类似的结果:
Code | funt | farc
------------| -----|---------
CAR | 1 | 2
CBB | 2 | 48
CC | 2 | 40
CIVG | 1 | 19
CIVR | 1 | 54
基本上,过滤器仅适用于我们提供的值,其余数据遵循通常的汇总逻辑。这可能使用 PostgreSQL 吗?
只需在 filter
中添加条件:
select code ,
count(1) filter (where value0 > 10000 or code not in ('CIVG', 'CIVR')) as funt,
count(1) ount,
sum(value2) filter (where value0 > 10000 or code not in ('CIVG', 'CIVR')) "farc" ,
sum(value2) "oarc"
from table
group by code
order by code;
我有一个数据集:
Code | Value0 | Value1 | Value2 |
------------| --------|----------- | -----------|
CAR | 44000 | 5.0 | 2 |
CBB | 1000 | 0.89 | 9 |
CC | 1450 | 1.56 | 5 |
CIVG | 21000 | 0.786 | 19 |
CIVR | 7000 | 134.6 | 15 |
CBB | 21000 | 440 | 39 |
CC | 14000 | 16.78 | 35 |
CIVG | 100 | 98.56 | 9 |
CIVR | 45000 | 15 | 54 |
我想基于列 code
进行聚合,使用过滤器 Only those rows should be summed which have value0 greater than 10000
。但是,此例外或过滤器应仅适用于代码 CIVG and CIVR
。此过滤器将不适用于其他代码。
我已经弄清楚的查询:
select code ,
count(1) filter (where value0 > 10000 ) as funt,
count(1) ount,
sum(value2) filter (where value0 > 10000 ) "farc" ,
sum(value2) "oarc"
from table
group by code
order by code;
使用它,我得到以下结果:
Code | funt | ount | farc | oarc |
------------| -----|---------| ------------|----------|
CAR | 1 | 1 | 2 | 2 |
CBB | 1 | 2 | 39 | 48 |
CC | 1 | 2 | 35 | 40 |
CIVG | 1 | 2 | 19 | 28 |
CIVR | 1 | 2 | 54 | 69 |
我想要的是除了 CIVG
和 CIVR
之外的变量不应该对它们应用过滤器,这会产生类似的结果:
Code | funt | farc
------------| -----|---------
CAR | 1 | 2
CBB | 2 | 48
CC | 2 | 40
CIVG | 1 | 19
CIVR | 1 | 54
基本上,过滤器仅适用于我们提供的值,其余数据遵循通常的汇总逻辑。这可能使用 PostgreSQL 吗?
只需在 filter
中添加条件:
select code ,
count(1) filter (where value0 > 10000 or code not in ('CIVG', 'CIVR')) as funt,
count(1) ount,
sum(value2) filter (where value0 > 10000 or code not in ('CIVG', 'CIVR')) "farc" ,
sum(value2) "oarc"
from table
group by code
order by code;