WHERE 子句中的 CASE WHEN 过滤日期
CASE WHEN in WHERE clause to filter the dates
我是 SQL 的超级初级,并尝试在 Teradata 的代码下方自动化我的日期参数:
SELECT
POST_DATE_YR,
POST_DATE_MN,
SERV_NAME,
MARKET_NAME,
COUNTRY_NAME
FROM
MY_TABLE
WHERE
CASE WHEN (EXTRACT(MONTH FROM CURRENT_DATE)+6)<=12
THEN (POST_DATE_YR = '2022' AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(MONTH FROM CURRENT_DATE)+6 )
ELSE
(POST_DATE_YR = '2022' AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND 12 )
or
(POST_DATE_YR = '2023' AND POST_DATE_MN Between 1 and EXTRACT(MONTH FROM CURRENT_DATE)-6 )
END
ORDER BY 1,2,3,4,5
我要定义的是:
如果 current_month+6 <=12,则将日期参数定义为年=2022 和月 current_month 和 current_month+6.
如果current_month+6 >12,则将日期参数定义为年=2022 和月在current_month 和12 之间加上年=2023 和月在1 和current_month-6 之间
它总是 7 个月的数据。
但是我执行的时候出错了。有人可以帮助实现这一目标吗?谢谢
CASE
表达式returns一个值; WHERE
子句需要一个或多个谓词(条件),而不是值。
SELECT
POST_DATE_YR,
POST_DATE_MN,
SERV_NAME,
MARKET_NAME,
COUNTRY_NAME
FROM
MY_TABLE
WHERE
(
EXTRACT(MONTH FROM CURRENT_DATE)+6)<=12
AND POST_DATE_YR = '2022'
AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE)
AND EXTRACT(MONTH FROM CURRENT_DATE)
)
OR
(
POST_DATE_YR = '2022'
AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND 12
)
OR
(
POST_DATE_YR = '2023'
AND POST_DATE_MN Between 1 and EXTRACT(MONTH FROM CURRENT_DATE)-6
)
ORDER BY 1,2,3,4,5
我是 SQL 的超级初级,并尝试在 Teradata 的代码下方自动化我的日期参数:
SELECT
POST_DATE_YR,
POST_DATE_MN,
SERV_NAME,
MARKET_NAME,
COUNTRY_NAME
FROM
MY_TABLE
WHERE
CASE WHEN (EXTRACT(MONTH FROM CURRENT_DATE)+6)<=12
THEN (POST_DATE_YR = '2022' AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(MONTH FROM CURRENT_DATE)+6 )
ELSE
(POST_DATE_YR = '2022' AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND 12 )
or
(POST_DATE_YR = '2023' AND POST_DATE_MN Between 1 and EXTRACT(MONTH FROM CURRENT_DATE)-6 )
END
ORDER BY 1,2,3,4,5
我要定义的是: 如果 current_month+6 <=12,则将日期参数定义为年=2022 和月 current_month 和 current_month+6.
如果current_month+6 >12,则将日期参数定义为年=2022 和月在current_month 和12 之间加上年=2023 和月在1 和current_month-6 之间
它总是 7 个月的数据。
但是我执行的时候出错了。有人可以帮助实现这一目标吗?谢谢
CASE
表达式returns一个值; WHERE
子句需要一个或多个谓词(条件),而不是值。
SELECT
POST_DATE_YR,
POST_DATE_MN,
SERV_NAME,
MARKET_NAME,
COUNTRY_NAME
FROM
MY_TABLE
WHERE
(
EXTRACT(MONTH FROM CURRENT_DATE)+6)<=12
AND POST_DATE_YR = '2022'
AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE)
AND EXTRACT(MONTH FROM CURRENT_DATE)
)
OR
(
POST_DATE_YR = '2022'
AND POST_DATE_MN Between EXTRACT(MONTH FROM CURRENT_DATE) AND 12
)
OR
(
POST_DATE_YR = '2023'
AND POST_DATE_MN Between 1 and EXTRACT(MONTH FROM CURRENT_DATE)-6
)
ORDER BY 1,2,3,4,5