【问题标题】:Case statement with datedfif and between带有 datediff 和 between 的 case 语句
【发布时间】:2024-01-10 00:38:01
【问题描述】:

我正在使用 Sybase IQ,并且有以下似乎不起作用的 SQL 代码。问题出在案例陈述上。在此先感谢

SELECT  a.cusid, start_date, effective_dt, 
case when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
case when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
case when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
case when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes' 

【问题讨论】:

  • 似乎不起作用不起作用怎么办?
  • “似乎不起作用”不是问题描述。你有错误吗?有哪些错误?你会得到意想不到的结果吗?您期望什么,实际结果如何?

标签: sql case sybase datediff sap-iq


【解决方案1】:

when 子句不需要每次都有 case 关键字。试试这个:

SELECT  a.cusid, start_date, effective_dt, 
case when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes'

【讨论】:

  • 感谢您的帮助
  • 快乐是我的。 :)
【解决方案2】:

你的语法有点不对劲。对于每个条件,您不需要 case

SELECT  a.cusid, start_date, effective_dt, 
CASE when DATEDIFF(DAY, start_date, effective_dt) >= 5476 THEN 'Green'
     when DATEDIFF(DAY, start_date, effective_dt) between 2921 AND 4575 THEN 'Red'
     when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 1096  AND 2920 THEN 'Blue'
     when DATEDIFF(DAY, start_date, effective_dt) BETWEEN 0 AND 1095 THEN 'Rose'
  ELSE NULL END as tier
FROM   tablea a
INNER JOIN tableb b
    ON a.cusid = b.cusid
WHERE   b.active = 'Yes' 

【讨论】:

  • 感谢您的帮助
最近更新 更多