除了 case when 之外的其他解决方案
other solution than case when
我有一个 firebird 数据库和这个查询:
select distinct
case
when exists (select * from fixvar
where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
then (select fix from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
else (select fix from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to))
end as fix,
case
when exists (select * from fixvar
where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
then (select var from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
else (select var from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
end as var
from fixvar
我得到了正确的结果,但我可以缩短它吗?
我想要的:我想查询字段fix
和var
。如果有一行 costcenter_id
是 10
,那么我想要相应的 fix
和 var
值,如果没有,那么我们没有的值不是 costcenter_id
(-1).
编辑:
示例数据:
如您所见,有两行。因此,如果 costcenter_id=10
存在一行,那么我想要 appr。 fix
和 var
值,如果没有包含此 costcenter_id
的行,那么我想要 fix
和 var
值,其中 costcenter_id=-1
.
我想,我有解决办法:
select
first 1 fix, var, costcenter_id
from
fixvar
where
costtype_id=7
and
2017 between extract(year from ct_from) and extract(year from ct_to)
and
costcenter_id in (-1, 10)
order by costcenter_id desc
我有一个 firebird 数据库和这个查询:
select distinct
case
when exists (select * from fixvar
where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
then (select fix from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
else (select fix from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to))
end as fix,
case
when exists (select * from fixvar
where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
then (select var from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
else (select var from fixvar where costtype_id=7 and extract(year from ct_from)<=2017 and
2017<=extract(year from ct_to) and costcenter_id=10)
end as var
from fixvar
我得到了正确的结果,但我可以缩短它吗?
我想要的:我想查询字段fix
和var
。如果有一行 costcenter_id
是 10
,那么我想要相应的 fix
和 var
值,如果没有,那么我们没有的值不是 costcenter_id
(-1).
编辑:
示例数据:
如您所见,有两行。因此,如果 costcenter_id=10
存在一行,那么我想要 appr。 fix
和 var
值,如果没有包含此 costcenter_id
的行,那么我想要 fix
和 var
值,其中 costcenter_id=-1
.
我想,我有解决办法:
select
first 1 fix, var, costcenter_id
from
fixvar
where
costtype_id=7
and
2017 between extract(year from ct_from) and extract(year from ct_to)
and
costcenter_id in (-1, 10)
order by costcenter_id desc