sql - 枢轴然后按价值分组
问题描述
我有一个logs
具有以下定义的表:
Column | Type | Collation | Nullable | Default
------------------+-----------------------+-----------+----------+---------
id | integer | | not null |
work_location_id | uuid | | not null |
hard_disk_id | integer | | not null |
以及works
具有以下定义的表:
Column | Type | Collation | Nullable | Default
-------------+-----------------------+-----------+----------+---------
id | integer | | not null |
location_id | uuid | | not null |
f_index | integer | | not null |
f_name | character varying(40) | | not null |
f_value | character varying(40) | | not null |
该logs
表包含以下数据:
id | work_location_id | hard_disk_id
----+--------------------------------------+--------------
1 | 40e6215d-b5c6-4896-987c-f30f3678f608 | 1
2 | 3f333df6-90a4-4fda-8dd3-9485d27cee36 | 2
3 | c17bed94-3a9c-4c21-be49-dc77f96d49dc | 3
4 | 6ecd8c99-4036-403d-bf84-cf8400f67836 | 4
5 | 6ecd8c99-4036-403d-bf84-cf8400f67836 | 5
该works
表具有以下数据:
id | location_id | f_index | f_name | f_value
----+--------------------------------------+---------+-------------+------------
1 | 40e6215d-b5c6-4896-987c-f30f3678f608 | 1 | plot_crop | pears
2 | 3f333df6-90a4-4fda-8dd3-9485d27cee36 | 1 | plot_crop | pears
3 | c17bed94-3a9c-4c21-be49-dc77f96d49dc | 1 | plot_crop | pears
4 | 1cdc7c05-0acd-46cb-b48a-4d3e240a4548 | 1 | plot_crop | pears
5 | dae1eee7-508f-4a76-8906-8ff7b8bfab26 | 1 | plot_crop | pears
6 | 6ecd8c99-4036-403d-bf84-cf8400f67836 | 1 | plot_id | 137
7 | 6ecd8c99-4036-403d-bf84-cf8400f67836 | 2 | farmer_name | John Smith
期望的输出
我希望能够查询这两个表并获得以下输出
location_id | plot_id | farmer_name
---------------------------------------+---------+-------------
40e6215d-b5c6-4896-987c-f30f3678f608 | None | None
3f333df6-90a4-4fda-8dd3-9485d27cee36 | None | None
c17bed94-3a9c-4c21-be49-dc77f96d49dc | None | None
6ecd8c99-4036-403d-bf84-cf8400f67836 | 137 | John Smith
注意 for location_id = 6ecd8c99-4036-403d-bf84-cf8400f67836
,两个值现在都显示在一行中。我尝试使用group by location_id
但没有用,我仍然得到重复。
我还创建了一个db-fiddle。
解决方案
这看起来像条件聚合:
select location_id,
max(f_value) filter (where f_name = 'plot_id') as plot_id,
max(f_value) filter (where f_name = 'farmer_name') as farmer_name
from t
group by location_id;
在其他数据库中,您只需使用:
max(case when f_name = 'plot_id' then f_value end) as plot_id
推荐阅读
- c - 为什么并行执行一个函数会显着减慢程序的速度?
- python - Python定时输入同时显示剩余时间
- mysql - 在更新插入新数据时,如果较旧,则更新时间戳
- admin - Infinispan 12.1.1.Final 在管理控制台(服务器管理控制台)中缺少缓存配置
- r - 将分组均值添加到具有分组频率和比例的数据框
- python - 调用 pandas describe 函数时排除一个值
- javascript - Google 登录显示错误 400:invalid_request Permission denied to generate login hint for target domain in Javascript
- android - Android 模拟器 - 如何在应用程序处于终止状态时测试通知
- python - 在 Earth Engine/GIS 中提取样带数据
- python - 删除重复项时重新排列字典列表的最惯用方法?