mysql 无法自动执行具有日期/时间列的SQL查询

r3i60tvu  于 2023-01-12  发布在  Mysql
关注(0)|答案(1)|浏览(112)

我想要一个SQL查询来生成上个月的数据,但由于年份的变化,我无法这样做。有人能帮助我正确的case when语句的问题。我认为它需要嵌套的case when语句。
我的专栏是:

  • createdmonth
  • createdyear
  • currentmonth
  • currentyear

我想对这些列应用条件。
下面是我的尝试:

EXTRACT (YEAR FROM DATE (CONVERT_TIMEZONE ('UTC','IST-05:30',u.createdTime))) as createdYear,
EXTRACT (YEAR FROM DATE (CONVERT_TIMEZONE ('UTC','IST-05:30',getdate()))) as currentyear,
EXTRACT (MONTH FROM DATE (CONVERT_TIMEZONE ('UTC','IST-05:30',u.createdTime))) as createdmonth,
EXTRACT (MONTH FROM DATE (CONVERT_TIMEZONE ('UTC','IST-05:30',getdate()))) - 1 as currentmonth,

CASE WHEN currentmonth = 0 THEN 12 
    CASE WHEN createdyear = currentyear then createdyear - 1 else createdyear 
ELSE currentmonth end as currentmonthtime,
y4ekin9u

y4ekin9u1#

您可以只使用DATE_ADD函数,它应该可以完成您所寻找的任务:

DATE_ADD(whatever_your_date_column_is, INTERVAL -1 MONTH);

相关问题