2017-07-14 111 views

回答

1

減去從今天月份的一天,你會得到前一個月的最後一天:

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

這包括當前時間。

要獲得午夜您可以將其截斷到有一天開始一個月核減:

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

兩個結果時間戳,但可以很容易地澆鑄爲字符串。

+0

哇,那太優雅了,不可能是真的:D – jirislav

+0

@jirislav:不,太簡單了:-) – dnoeth

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)

正則表達式方式似乎對我更可讀,所以我使用該版本。

相關問題