【问题标题】:SQL: Get min and max for groups in ordered tableSQL:获取有序表中组的最小值和最大值
【发布时间】: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


    【解决方案1】:

    这是一个孤岛问题。我会推荐行号的差异:

    select sample_id, layer_type, 
           max(depth) as top, min(depth) as bottom
    from  (select t.*,
                  row_number() over (partition by sample_id order by depth) as seqnum,
                  row_number() over (partition by sample_id, layer_type order by depth) as seqnum_lt
           from sample_table t
          ) t
    group by sample_id, layer_type, (seqnum - seqnum_lt)
    order by sample_id, min(depth) desc;
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2019-07-13
      • 2010-11-23
      • 2011-08-16
      • 2017-12-13
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多