sql - postgresql 按最大字符串长度聚合
问题描述
我有一对多的关系。在这种情况下,它是一个pipelines
可以有许多segments
. 该segments
实体有一列列出与该管道关联的井。此列纯粹是信息性的,仅作为逗号分隔列表从监管来源更新,因此数据类型为text
.
我想要做的是列出所有pipelines
并显示segment
具有最相关井的列。每口井都用标准化的土地位置标识(每口井的文本长度相同)。我还在 上做其他聚合函数segments
,所以我的查询看起来像这样(我必须简化它,因为它非常大):
SELECT pipelines.*, max(segments.associated_wells), min(segments.days_without_production), max(segments.production_water_m3)
FROM pipelines
JOIN segments ON segments.pipeline_id = pipelines.id
GROUP BY pipelines.id
这会选择associated_wells
具有最高字母值的,这是有道理的,但不是我想要的。
max(length(segments.associated_wells))
将选择我想要的记录,但只显示长度。我需要显示列值。
如何根据字符串长度进行聚合但显示值?
这是我所期待的一个例子:
细分实体:
| id | pipeline_id | associated_wells | days_without_production | production_water_m3 |
|----|-------------|--------------------------|-------------------------|---------------------|
| 1 | 1 | 'location1', 'location2' | 30 | 2.3 |
| 2 | 1 | 'location1' | 15 | 1.4 |
| 3 | 2 | 'location1' | 20 | 1.8 |
管道实体:
| id | name |
|----|-------------|
| 1 | 'Pipeline1' |
| 2 | 'Pipeline2' |
| | |
期望的查询结果:
| id | name | associated_wells | days_without_production | production_water_m3 |
|----|-------------|--------------------------|-------------------------|---------------------|
| 1 | 'Pipeline1' | 'location1', 'location2' | 15 | 2.3 |
| 2 | 'Pipeline2' | 'location1' | 20 | 1.8 |
| | | | | |
解决方案
如果我理解正确,你想要DISTINCT ON
:
SELECT DISTINCT ON (p.id) p.*, s.*
FROM pipelines p JOIN
segments s
ON s.pipeline_id = p.id
ORDER BY p.id, LENGTH(s.associated_wells) DESC;
推荐阅读
- java - Spring Boot 循环依赖与接口
- php - 如何从 react、axios 和 dropzone 前端使用 php 保存文件?
- entity-framework - OData - Entity Framework Core - 如何将 OData 参数从 Controller 注入到 Linq 查询中
- ruby - 如何在 Pry 控制台中提供自定义方法
- python - 将数据帧分区到重叠段
- spring-data-mongodb - Spring data MongoDB查询具有BigDecimal类型字段的文档
- c++ - C++ ^ 运算符与函数一起使用
- html - 在网页中制作图表
- java - 如何捕获 GWT TextBox KeyDown 重复
- audio - 如何将音频文件设置为某些特征?