如何获取 Impala 中上个月的最后一天?
How to get last day of previous month in Impala?
我想在 Impala 中获取 上个月的最后一天 作为任何类型(最好是字符串)。
应该很好可读和有效。
使用 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
使用 extract & 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)
可以轻松转换为字符串
regexp 方式对我来说似乎更具可读性,所以我正在使用那个版本。
从今天减去本月的第几天,得到上个月的最后一天:
date_sub(now(), day(now())
这包括当前时间。
要获得午夜,您可以将其截断到月初并减去一天:
date_sub(trunc(now(), 'month'), 1)
两者都会产生时间戳,但可以轻松转换为字符串。
我想在 Impala 中获取 上个月的最后一天 作为任何类型(最好是字符串)。
应该很好可读和有效。
使用 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
使用 extract & 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)
regexp 方式对我来说似乎更具可读性,所以我正在使用那个版本。
从今天减去本月的第几天,得到上个月的最后一天:
date_sub(now(), day(now())
这包括当前时间。
要获得午夜,您可以将其截断到月初并减去一天:
date_sub(trunc(now(), 'month'), 1)
两者都会产生时间戳,但可以轻松转换为字符串。