SQL:提取与聚合相关的值

时间:2017-06-14 14:55:30

标签: sql max aggregate teradata min

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

ID1,ID2,价值

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

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.

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

我试图找出提供以下方法的方法: ID1,Min(ID2),Max(ID2),以及与min / max id2关联的值:

一个,1,3,5,7-

我提出的唯一方法是:

    <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
      <div class="collapse" id="a" *ngIf="a">
        <ul class="navbar-nav">
          <li class="nav-item"><a class="nav-link" href="#">a</a></li>
          <li class="nav-item"><a class="nav-link" href="#">b</a></li>
          <li class="nav-item"><a class="nav-link" href="#">c</a></li>
        </ul>
      </div>
      <div class="collapse" id="b" *ngIf="b">
        <ul class="navbar-nav">
          <li class="nav-item"><a class="nav-link" href="#">p</a></li>
          <li class="nav-item"><a class="nav-link" href="#">q</a></li>
          <li class="nav-item"><a class="nav-link" href="#">r</a></li>
        </ul>
      </div>
      <div class="collapse" id="c" *ngIf="c">
        <ul class="navbar-nav">
          <li class="nav-item"><a class="nav-link" href="#">x</a></li>
          <li class="nav-item"><a class="nav-link" href="#">y</a></li>
          <li class="nav-item"><a class="nav-link" href="#">z</a></li>
        </ul>
      </div>
    </nav>

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

1 个答案:

答案 0 :(得分: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