如何在Impala获得上个月的最后一天?

时间:2017-07-14 07:53:25

标签: sql impala

我想在Impala中将上个月的最后一天作为任何类型(最好是字符串)。

它应该可读有效

2 个答案:

答案 0 :(得分:1)

从今天开始减去日期,你得到上个月的最后一天:

date_sub(now(), day(now())

这包括当前时间。

要到午夜,您可以将其截断到月初并减去一天:

date_sub(trunc(now(), 'month'), 1)

两者都会产生时间戳,但可以轻松地转换为字符串。

答案 1 :(得分:0)

使用 regexp

SELECT 
    days_sub(
        regexp_replace( 
            regexp_extract(
                cast(now() AS string),
                '[\\d-]{10}',
                0
            ), /* Get today in format: YYYY-mm-dd */
            '\\d{2}$', '01'
        ), /* Get the first day of this month: YYYY-mm-01 */
        1
    ) /* Subtract one day */
    AS DAY

单线

SELECT days_sub(regexp_replace(regexp_extract(cast(now() AS string), '[\\d-]{10}', 0),'\\d{2}$', '01'), 1) AS DAY

使用提取& concat 函数

SELECT 
    days_sub(
            concat(
                cast(extract(now(),'year') AS string), /* Extract current year*/
                '-',
                regexp_replace(
                    cast(extract(now(),'month') AS string), /* Extract current month */
                    '^\\d$', '0\\0'
                ), /* Make sure the month has two digits e.g. from '1' create '01' */
                '-01'
            ),  /* Concat current year, month and day one */
            1 
        ) /* Subtract one day */
        AS DAY

单线

SELECT days_sub(concat(cast(extract(now(),'year') AS string), '-', regexp_replace(cast(extract(now(),'month') AS string), '^\\d$', '0\\0'), '-01'), 1) AS DAY

比较

两个选项都会产生类型TIMESTAMP的相同结果:

2017-06-30 00:00:00

使用cast(result as string)

可以轻松地将其转换为字符串

正则表达式方式对我来说似乎更具可读性,因此我使用该版本。