【问题标题】:SQL: pulling in values associated with aggregatesSQL:拉入与聚合相关的值
【发布时间】:2017-11-16 19:26:00
【问题描述】:

假设我有一个包含以下列的表格:

ID1、ID2、值

对于每个ID1,可以有多个ID2和对应的值,即:

a,1,5
a,2,6
a,3,7

.

Edit: Simpler version of ask:
How can I pull ID1, Max(ID2), Value without having to group on value (i want 
to pull the value that corresponds to the max(id2) and without having to do a second join.

我正在尝试找出一种方法来提供以下内容: ID1、Min(ID2)、Max(ID2),以及与最小/最大 id2 关联的值:

a,1,3,5,7

我想出的唯一方法是:

select 
a.id1, a.min_id2, a.max_id2, b.value as min_value, c.value as max_value
from (select id1, min(id2) as min_id2, max(id2) as max_id2) from table group by 1) a
left outer join (select id1, id2, value from table) b on a.min_id2 = b.id2
left outer join (select id1, id2, value from table) c on a.max_id2 = c.id2

这是一个假设示例,但在我的数据上运行此示例需要很长时间。希望可能有某种我不知道的捷径。

【问题讨论】:

    标签: sql max aggregate teradata min


    【解决方案1】:

    如果您希望在一行中同时显示最小值/最大值,您可以使用多个 OLAP 函数(但所有函数都将在 Explain 中一步计算):

    SELECT t.*, 
       -- max id2 
       Max(id2) Over (PARTITION BY id1),
       -- and corresponding value
       Last_Value(value)
       Over (PARTITION BY id1
             ORDER BY id2
             ROWS BETWEEN Unbounded Preceding AND Unbounded Following)
    FROM table AS t  
    QUALIFY -- row with min id2
       Row_Number()
       Over (PARTITION BY id1
             ORDER BY id2) = 1
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多