hive查询按年份和id获取日期列组的最小值和最大值

xqnpmsa8  于 2021-06-26  发布在  Hive
关注(0)|答案(1)|浏览(837)

我有一个有两列的表,id和date。我想得到那个特定id的最大和最小日期。下面是示例数据和我想要的结果示例数据

id  date_col

123 2015-05-01 04:00:00

123 2017-04-01 04:00:00

123 2017-09-01 04:00:00

123 2014-09-01 04:00:00

123 2012-12-01 05:00:00

123 2016-08-01 04:00:00

123 2014-05-01 04:00:00

123 2016-10-01 04:00:00

我期待的结果

123 2014-05-01   2014-09-01

123 2015-05-01

123 2016-08-01   2016-10-01

123 2017-04-01   2017-09-01

我尝试使用下面的多重查询,但我不会按年份排序

SELECT id,MAX(date_col) AS maxdate_col,MIN(date_col) AS mindate_col FROM table GROUP BY id 

SELECT id,MAX(date_col) AS max_votes,MIN(date_col) AS mindate_col,YEAR(date_col) FROM test GROUP BY id,YEAR(date_col)
ssgvzors

ssgvzors1#

试试这个

SELECT id
        ,MIN(date_col) AS mindate_col
        ,(CASE WHEN MAX(date_col) <> MIN(date_col) THEN MAX(date_col) END)  AS maxdate_col
        ,YEAR(date_col) AS year_col
FROM    test 
GROUP BY id,YEAR(date_col)
ORDER BY id,year_col

如果你只想要 date 部分,你可以投 CAST(date_col AS DATE)

相关问题