下面是我的Postgres表:
表:
+------+-----------------+---------+
| sku | properties | value |
|------+-----------------+---------|
| 1 | Family_ID | 21 |
| 1 | Class_ID | 21 |
| 2 | Family_ID | 20 |
| 2 | Class_ID | 21 |
| 3 | Family_ID | 21 |
| 3 | Class_ID | 21 |
+------+-----------------+---------+
Family_ID
和Class_ID
是21
。期望的返回值:
+------+-----------------+---------+
| sku | properties | value |
|------+-----------------+---------|
| 1 | Family_ID | 21 |
| 1 | Class_ID | 21 |
| 3 | Family_ID | 21 |
| 3 | Class_ID | 21 |
+------+-----------------+---------+
Family_ID
is20
和Class_ID
is中获取数据21
。期望的返回值:
+------+-----------------+---------+
| sku | properties | value |
|------+-----------------+---------|
| 2 | Family_ID | 20 |
| 2 | Class_ID | 21 |
+------+-----------------+---------+
该查询:
select sku
from tablename
group by sku
having
max(case when properties = 'Family_ID' then value end) = 21
and
max(case when properties = 'Class_ID' then value end) = 21
返回所有sku
满足条件的,您可以将其与运算符一起使用,IN
如下所示:
select * from tablename
where sku in (
select sku
from tablename
group by sku
having
max(case when properties = 'Family_ID' then value end) = 21
and
max(case when properties = 'Class_ID' then value end) = 21
)
您还可以使用MAX()窗口函数:
select t.sku, t.properties, t.value
from (
select *,
max(case when properties = 'Family_ID' then value end) over (partition by sku) family_id,
max(case when properties = 'Class_ID' then value end) over (partition by sku) class_id
from tablename
) t
where t.family_id = 21 and t.class_id = 21
参见演示。
结果:
> sku | properties | value
> --: | :--------- | ----:
> 1 | Family_ID | 21
> 1 | Class_ID | 21
> 3 | Family_ID | 21
> 3 | Class_ID | 21
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句