我在 postgresql 中有下表讓我們稱之為 table1
| 物體編號 | 物體組 | 價值 |
|---|---|---|
| 1 | 一種 | 5000 |
| 2 | 一種 | 4000 |
| 3 | 一種 | 3000 |
| 4 | 一種 | 2000年 |
| 5 | 一種 | 1000 |
| 1 | 乙 | 5000 |
| 2 | 乙 | 4800 |
| 3 | 乙 | 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 組時進行縮放。
uj5u.com熱心網友回復:
您可以嘗試使用以下方法:
- 一個 group by 和一個帶有子句
- 在具有不同值的相似
entity_ids 但不同的entitygroups 上進行自聯接。
查詢#1
select
count(1)
from (
select
entityid
from
table1
group by
entityid
having
count(distinct entitygroup) > 1 and
min(value) <> max(value)
) t1;
| 數數 |
|---|
| 2 |
查詢#2
select
entityid
from
table1
group by
entityid
having
count(distinct entitygroup) > 1 and
min(value) <> max(value);
| 物體ID |
|---|
| 2 |
| 3 |
查詢 #3
select
count(distinct t1.entityid)
from
table1 t1
inner join
table1 t2 on t1.entityid = t2.entityid and
t1.entitygroup < t2.entitygroup and
t1.value <> t2.value;
| 數數 |
|---|
| 2 |
查詢 #4
select
count(distinct t1.entityid)
from
table1 t1
inner join
table1 t2 on t1.entityid = t2.entityid and
t1.entitygroup < t2.entitygroup and
abs(t1.value - t2.value)>0;
| 數數 |
|---|
| 2 |
查詢 #5
select distinct
t1.entityid
from
table1 t1
inner join
table1 t2 on t1.entityid = t2.entityid and
t1.entitygroup < t2.entitygroup and
abs(t1.value - t2.value) > 0;
| 物體ID |
|---|
| 2 |
| 3 |
查看 DB Fiddle 上的作業演示
uj5u.com熱心網友回復:
您可以count(distinct)與子查詢一起使用:
select count(*) from (select t1.id, count(distinct t1.value) h from table1 t1 group by t1.id) t2
where t2.h = (select count(*) from table1 t3 where t3.id = t2.id) and t2.h > 1;
輸出:
count
-----
2
對應的物體 ID 為 ( select t2.id from ...):
id
-----
2
3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353899.html
標籤:sql PostgreSQL 通过...分组
