我有一个看起来像这样的桌子
jjsc_job_no jjsc_from_status jjsc_time jjsc_wf_userid
123456 D 2012-07-01 13:33:27 804
123456 E 2014-04-08 03:22:35 804
123457 D 2012-07-01 13:33:27 805
123457 E 2014-04-08 03:22:35 806
我想要一个结果,如果jjsc_from_status = 'E'
然后在jjsc_from_status = 'D'
具有不同的jjsc_wf_userid
时检查同一作业。如果是,则返回3
,否则返回0
我写了这样的东西,但是说语法错误
select case jjsc_from_status
when 'E' then if(select jjsc_from_status from jdwf_job_status_cycle where jjsc_wf_userid = jjsc_wf_userid, 0,3 )
when 'D' then 9
end as estimatedunits
from jdwf_job_status_cycle
where jjsc_time>='$fDate' and jjsc_time<='$tDate'
order by jjsc_time
预期结果是
estimatedunits
9
0
9
3
答案 0 :(得分:1)
您可以使用嵌套的CASE和EXISTS来做到这一点:
select
case j.jjsc_from_status
when 'D' then 9
when 'E' then
case
when exists (
select 1 from jdwf_job_status_cycle
where jjsc_job_no = j.jjsc_job_no and jjsc_from_status = 'D'
and jjsc_wf_userid <> j.jjsc_wf_userid)
then 3
else 0
end
end as estimatedunits
from jdwf_job_status_cycle j
where jjsc_time>='$fDate' and jjsc_time<='$tDate'
order by jjsc_time
请参见demo(不带WHERE子句)。
结果:
| estimatedunits |
| -------------- |
| 9 |
| 0 |
| 9 |
| 3 |
答案 1 :(得分:1)
您应该始终为表使用别名!
在这种情况下,您想在子查询中使用驱动器表中的数据,因此为它们添加2个不同的别名:
select
case jsc.jjsc_from_status
when 'E' then if(exists(select jjsc_from_status from jdwf_job_status_cycle jsc2 where jsc2.jjsc_job_no = jsc.jjsc_job_no and jsc2.jjsc_from_status = 'D' and jsc2.jjsc_wf_userid <> jsc.jjsc_wf_userid), 3, 0)
when 'D' then 9
end as estimatedunits
from jdwf_job_status_cycle jsc
where jsc.jjsc_time>='$fDate' and jsc.jjsc_time<='$tDate'
order by jsc.jjsc_time
答案 2 :(得分:0)
语法错误的原因是将返回字符串的select
放在if
子句中,您应该在if
子句中修改查询以返回布尔结果,例如: / p>
select case jjsc_from_status
when 'E' then if( (select count(jjsc_from_status) from jdwf_job_status_cycle as t2 where t1.jjsc_wf_userid = t2.jjsc_wf_userid) > 0, 0,3 )
when 'D' then 9
end as estimatedunits
from jdwf_job_status_cycle as t1
where jjsc_time>='$fDate' and jjsc_time<='$tDate'
order by jjsc_time