简体   繁体   English

如何根据其他 2 列选择 1 列的最大值和最小值?

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

I'm trying to get the max and min date values in column C based on the (column A, column B) unique pair combinations.我正在尝试根据(A 列,B 列)唯一对组合获取 C 列中的最大和最小日期值。

Suppose I have a table like:假设我有一张像:

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

The output I want to get is:我想得到的输出是:

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

My attempt query has been taking 20 mins to run with no output yet (just tried to get max date from column C for now):我的尝试查询运行了 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
)

Just use two conditions:只需使用两个条件:

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
                 ) ;
  

You can use two queries that group by column_a and column_b , one with the max and one with the min of column_c , and then union all them:您可以使用两个按column_acolumn_b分组的查询,一个是column_c的最大值,另一个是column_c ,然后union all它们column_c

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

you can create a temporary view and GROUP BY the desired columns您可以创建一个临时视图和 GROUP BY 所需的列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM