【发布时间】:2019-12-18 16:08:21
【问题描述】:
我有一张带有钻孔样品的桌子。该表针对每个深度单位都有一行,列出了该深度的普遍材料类型。从这张表中,我想获得每种图层类型的顶部(最大)和底部(最小)深度。这如何在 SQL 中完成?如果我使用“group by”,深度排序会丢失,如果我使用“order by”,我不能使用“min(depth)”和“max(depth)”?
示例输入表
|sampleid | layertype | depth|
+----------------------------+
| 1 | sand | 0 |
| 1 | sand | -1 |
| 1 | peat | -2 |
| 1 | sand | -3 |
| 1 | sand | -4 |
| 1 | sand | -5 |
| 1 | clay | -6 |
| 1 | clay | -7 |
| 1 | clay | -8 |
| 1 | sand | -9 |
| 1 | sand | -10 |
| 1 | sand | -11 |
+----------------------------+
所需的输出表:
|sampleid | layertype | top | bottom |
+------------------------------------+
| 1 | sand | 0 | -1 |
| 1 | peat | -2 | -2 |
| 1 | sand | -3 | -5 |
| 1 | clay | -6 | -8 |
| 1 | sand | -9 | -11 |
+------------------------------------+
这种问题可能在 StackOverflow 上被问过很多次,但我找不到答案或重复,也许我没有使用正确的搜索词?
【问题讨论】:
标签: sql postgresql