【发布时间】:2021-12-21 20:09:42
【问题描述】:
我在 postgresql 中有下表,我们称之为table1
| entity id | entity group | value |
|---|---|---|
| 1 | A | 5000 |
| 2 | A | 4000 |
| 3 | A | 3000 |
| 4 | A | 2000 |
| 5 | A | 1000 |
| 1 | B | 5000 |
| 2 | B | 4800 |
| 3 | B | 2700 |
- 我需要找出在不同实体组中具有不同值的实体的数量。
- 在上面的示例中,答案将是 2 (entity_id: 2,3)。
我有一个 hacky 方法如下
with entity_diff as (
with entitya as (
select entity_id,
value as value_group_a
from table1
where entity_group = 'A'
),
entityb as (
select entity_id,
value as value_group_b
from table1
where entity_group = 'B'
)
select entitya.entity_id,
entitya.value_group_a - entityb.value_group_b as value_diff
from entitya
inner join entityb on entitya.entity_id = entityb.entity_id
)
select count(*) from from entity_diff
where abs(entity_diff.value_diff) > 0;
有没有更简单的方法来获得这个答案,当我需要比较 3 或 4 个组时也可以扩展。
【问题讨论】:
标签: sql postgresql group-by