我想在Impala中将上个月的最后一天作为任何类型(最好是字符串)。
它应该可读和有效。
答案 0 :(得分:1)
从今天开始减去日期,你得到上个月的最后一天:
date_sub(now(), day(now())
这包括当前时间。
要到午夜,您可以将其截断到月初并减去一天:
date_sub(trunc(now(), 'month'), 1)
两者都会产生时间戳,但可以轻松地转换为字符串。
答案 1 :(得分:0)
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
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)
正则表达式方式对我来说似乎更具可读性,因此我使用该版本。