SQL:对于每个Col1组,返回具有Max(Col3)的Col2值

时间:2018-11-09 00:23:19

标签: sql

我该如何选择?

<template>
 ...
</template>

<script>
import store from "../store/index";

export default {
  props: [...],
  store,
  ...
}

给出

C1 C2 C3

SELECT C1, C2, MAX(C3)
  FROM Table
  GROUP BY C1

我想退货:

C1 C2 C3

1  A  10
1  B  20
1  C  30
2  A  70
2  B  60
2  C  50

2 个答案:

答案 0 :(得分:0)

有条件的聚合是首先想到的。这几乎可以在任何数据库中工作,因为它使用了标准的SQL功能:

select col1,
       max(case when seqnum = 1 then col2 end) as col2,
       max(col3) as col3
from (select t.*,
             row_number() over (partition by col1 order by col3 desc) as seqnum
      from t
     ) t
group by col1;

类似的方法使用相关的子查询:

select t.*
from t
where t.col3 = (select max(t2.col3) from t t2 where t2.col1 = t.col1);

实际上,这应该具有更好的性能,尤其是在(col1, col3)上使用索引时。

答案 1 :(得分:0)

这是您的查询的解决方案。

select c1,
       max(case when section = 1 then c2 end) as c2,
       max(c3) as c3
from (select t.*,
             row_number() over (partition by c1 order by c3 desc) as section
      from TableName t
     ) t
group by c1