select ac1.ACCT_CODE,
ac1.PERIOD,
ac1.MONTH,
ac1.YEAR,
ac1.PRD_BDGT,
ac2.ACCT_CODE,
ac2.PERIOD,
ac2.MONTH,
ac2.YEAR,
ac2.PRD_BDGT
from account ac1, account ac2
where ac1.acct_code='075200'
and ac1.year=1994
and ac1.period between 1 and 6
and ac2.acct_code=ac1.acct_code
and ac2.year=1995
and ac2.period =ac1.period
union
select ac3.ACCT_CODE,
ac3.PERIOD,
ac3.MONTH,
ac3.YEAR,
ac3.PRD_BDGT,
ac4.ACCT_CODE,
ac4.PERIOD,
ac4.MONTH,
ac4.YEAR,
ac4.PRD_BDGT
from account ac3, account ac4
where ac3.acct_code='075200'
and ac3.year=1995
and ac3.period between 7 and 12
and ac4.acct_code=ac3.acct_code
and ac4.year=1996
and ac4.period=ac3.period
答案 0 :(得分:2)
使用OR
:
select ac1.ACCT_CODE,
ac1.PERIOD,
ac1.MONTH,
ac1.YEAR,
ac1.PRD_BDGT,
ac2.ACCT_CODE,
ac2.PERIOD,
ac2.MONTH,
ac2.YEAR,
ac2.PRD_BDGT
from account ac1, account ac2
where ac1.acct_code='075200'
and ac2.acct_code=ac1.acct_code
and ac2.period =ac1.period
and ((ac1.year=1994
and ac1.period between 1 and 6
and ac2.year=1995
) OR
(ac1.year=1995
and ac1.period between 7 and 12
and ac2.year=1996))
答案 1 :(得分:2)
您的查询正在执行两个非常相似的查询中的union
,其中唯一的区别是where
子句中的某些条件。您可以使用or
子句中的where
轻松地将它们组合起来。
以下查询还修复了join
语法:
select ac1.ACCT_CODE, ac1.PERIOD, ac1.MONTH, ac1.YEAR, ac1.PRD_BDGT, ac2.ACCT_CODE,
ac2.PERIOD, ac2.MONTH, ac2.YEAR, ac2.PRD_BDGT
from account ac1 join
account ac2
on ac2.period = ac1.period and
ac2.acct_code = ac1.acct_code
where ac1.acct_code='075200' and
((ac1.year = 1994 and
ac1.period between 1 and 6
ac2.year=1995
) or
(ac1.year=1995 and
ac1.period between 7 and 12 and
ac2.year=1996
)
);
如果此查询实际解决了您的业务问题,我会感到惊讶。在accounts
表上进行自联接是可疑的。通常,聚合是人们需要的,但我不能说出查询的目的。