2
select 
sc.locationid, --here to get a result
(
   if month(date()) between 8 and 12 then @semTerm = 'S1'
   else @semTerm = 'S2'
   end if
)as @semTerm

from student_class sc
where @semTerm = sc.semester
;

在 db2 学生管理系统中。只读访问。期望的结果是如果 1 月到 6 月,S2,否则如果 8 月到 12 月,S1。尝试根据当前日期戳设置变量,其中月份被隔离,然后分配给变量,然后与 student_class 表中的列进行比较。

也尝试过案例陈述,但没有运气。无法在选择语句上方无错误地声明 @semTerm。还查看了where子句解决方案。我在左外野吗?看起来很简单,但在语法上很挣扎。较大语句的一部分,其中 locationID 作为 student_class 中的一列。

4

2 回答 2

1

您不能真正IF在简单SELECT语句中使用语句,您必须使用CASE

select 
    sc.locationid, --here to get a result
    case 
      when month(current date) between 8 and 12 then 'S1'
      when month(current date) between 1 and 6  then 'S2'
      else ''
    end as semTerm 
from 
    student_class sc

如果您只想找到当前学期的学生,那么您需要将CASE语句移到WHERE子句中:

select 
    sc.locationid, --here to get a result
    sc.semester,
    ...
from 
    student_class sc
where 
    sc.semester = case 
                    when month(current date) between 8 and 12 then 'S1'
                    when month(current date) between 1 and 6  then 'S2'
                    end
于 2013-09-03T19:50:11.877 回答
0

CASE表达式通常是在语句中实现条件逻辑的方式SELECT。但是,如果您不必在每一行都重新计算它会更有效,对吧?

一种方法是在公用表表达式中“预先计算”它,并将其作为您的选择标准加入:

with v (semester) as
( values 
    case 
      when month(current date) > 7 then 'S1'
      when month(current date) < 7 then 'S2'
                                   else null
    end
)
select 
    sc.locationid, 
    sc.semester,
    ...
from 
    student_class sc
join
    v                on  sc.semester = v.semester;

或者

如果您发现当前学期值在许多其他地方有用,另一种方法可能是创建一个“全局会话变量”来保存该值。(z/OS 除外)

create or replace variable
    v_sememster  char(2)
      default 
        case 
          when month(current date) > 7
            then 'S1'
          when month(current date) < 7
            then 'S2'
          else   null
        end;

然后你可以有一个非常简单的查询:

select 
    sc.locationid, 
    sc.semester,
    ...
from 
    student_class sc
where 
    sc.semester = v_semester;
于 2013-09-03T22:51:20.627 回答