where 子句中的 case 语句,我的查询有什么问题?

Case statement in where clause, what's wrong with my query?

谁能告诉我我的代码有什么问题?

SELECT 
    *
FROM    
    TABLE.NAME
WHERE 
    TICKET_GROUP IN 
        CASE WHEN ticket_created_at <= CAST('2022-04-01' AS DATE) 
                 THEN  (1500003613882, 360013692813, 114095263234) 
                 ELSE (1500001610322, 360005931333, 1260811380530) 
        END

我收到这个错误

line 8:20: mismatched input 'IN'. Expecting: 'AND', 'EXCEPT', 'FETCH', 'GROUP', 'HAVING', 'INTERSECT', 'LIMIT', 'OFFSET', 'OR', 'ORDER', 'UNION', <EOF>

我尝试将其更改为“=”而不是 IN,但没有成功。

如果您想“动态地”定义 IN 值,那么您可以在 case 语句的结果表达式中移动 TICKET_GROUP IN

WHERE 
    CASE 
       WHEN ticket_created_at <= CAST('2022-04-01' AS DATE) 
          THEN TICKET_GROUP IN (1500003613882, 360013692813, 114095263234) 
       ELSE TICKET_GROUP IN (1500001610322, 360005931333, 1260811380530) 
    END

或者只使用 ORAND 的布尔逻辑:

WHERE 
    (ticket_created_at <= CAST('2022-04-01' AS DATE) AND TICKET_GROUP IN (1500003613882, 360013692813, 114095263234))
    OR (TICKET_GROUP IN (1500001610322, 360005931333, 1260811380530))

一个CASE表达式总是产生一个,而不是另一个表达式。因此,您必须像这样构建 WHERE 子句:

WHERE 
   ( ticket_created_at <= CAST('2022-04-01' AS DATE) 
     AND TICKET_GROUP IN (1500003613882, 360013692813, 114095263234) 
   )
   OR (
     ticket_created_at > CAST('2022-04-01' AS DATE)
     AND TICKET_GROUP IN (1500001610322, 360005931333, 1260811380530) 
   )

此外,我们可以使用 NULLIF() 来简化 SELECT 子句中的 CASE 表达式,如下所示:

SELECT 
    *,
    COALESCE(NULLIF(C_220_COUNTRY_CODE, 'N/A'), COUNTRY_SALES_POD) AS FINAL_COUNTRY_CODE

FROM    
    CUSTOMER_OPS_HISTORICAL.ZENDESK_HISTORICAL_TICKET_CONSOLIDATED_CUSTOMER_OPS_DASHBOARD
WHERE 
   ( ticket_created_at <= CAST('2022-04-01' AS DATE) 
     AND TICKET_GROUP IN (1500003613882, 360013692813, 114095263234) 
   )
   OR (
     ticket_created_at > CAST('2022-04-01' AS DATE)
     AND TICKET_GROUP IN (1500001610322, 360005931333, 1260811380530) 
   )