2016-12-14 63 views
0

我有一个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 

我得到正确的结果,但我可以做短?我想查询fixvar。如果有一行,其中costcenter_id10,那么我想要相应的fixvar的值,如果不是,那么这些值就是我们没有的costcenter_id(-1)。

编辑:

的样本数据:

enter image description here

正如你看到的,有两排。所以,如果一行存在costcenter_id=10,那么我想要appr。 fixvar的值,如果没有这个costcenter_id的行,那么我想要fixvar的值,其中的costcenter_id=-1

+1

样本数据和预期的结果将真正帮助解释你想要做什么。 –

+0

[Firebird SQL挑战 - 在选择返回的两行时返回一行有数据]可能重复(http://stackoverflow.com/questions/14451183/firebird-sql-challenge-return-one-row-that-has -the-data-when-select-returned-t) – Serg

+0

谢谢Serg,那是通过我的解决方案。 – derstauner

回答

0

我想,我有解决方案:

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 
相关问题