如何 select 基于其他 2 列的 1 列的最大值和最小值?

How to select max and min of 1 column based on other 2 columns?

我正在尝试根据(A 列、B 列)唯一对组合获取 C 列中的最大和最小日期值。

假设我有一个 table 比如:

column_A column_B column_C
A        1        2019-08-11
A        1        2018-11-12
A        1        2017-11-12
A        11       2020-03-03
A        11       2021-01-10
A        11       2021-02-02
B        2        2020-11-11
B        2        2020-12-12

我想要得到的输出是:

column_A column_B column_C
A        1        2019-08-11
A        1        2017-11-12
A        11       2020-03-03
A        11       2021-02-02
B        2        2020-11-11
B        2        2020-12-12

我的尝试查询已花费 20 分钟到达 运行,但还没有输出(现在只是尝试从 C 列获取最大日期):

SELECT column_A, column_B, column_C FROM table_name
WHERE column_C IN (
   SELECT MAX(column_C) FROM table_name
   GROUP BY column_A, column_B
)

只需使用两个条件:

select t.*
from t
where column_c = (select max(t2.colc)
                  from table_name t2
                  where t2.column_A = t.column_A and t2.column_B = t.column_B
                 ) or
      column_c = (select min(t2.colc)
                  from table_name t2
                  where t2.column_A = t.column_A and t2.column_B = t.column_B
                 ) ;
  

您可以使用按 column_acolumn_b 分组的两个查询,一个使用最大值 column_c,另一个使用最小值 column_c,然后 union all 它们:

SELECT   column_a, column_b, MAX(column_c)
FROM     table_name
GROUP BY column_a, column_b
UNION ALL
SELECT   column_a, column_b, MIN(column_c)
FROM     table_name
GROUP BY column_a, column_b

您可以创建临时视图并按所需列进行分组

select column_a,column_b,max(column_c) as max_column_c
from (select column_a,column_b,column_c,to_char(column,'YYYY') as year
from table_t) aa
group by column_a,column_b,year