从另一个表/子查询中检索数据

时间:2014-09-11 15:57:47

标签: sql oracle11g

SQL#1就像我期望的那样工作。但是,我需要将3个字段(account,journal_id和journal_date)添加到另一个表的结果中.SQL#2将结果中需要的3个字段返回给SQL#1。它还返回asset_id字段,因为SQL的结果#2必须与SQL#1中的asset_ID字段相关。

我想知道SQL#1中的子查询是否会返回3个字段。我是sql的新手,并且不知道在SQL#1中从哪个子查询开始。任何有关此问题的帮助将不胜感激。谢谢。

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~

SQL#1

SELECT 
pa.BUSINESS_UNIT, 
pa.DESCR,
pdr.DEPTID, 
pdr.ASSET_ID, 
pdr.ACCOUNT_AD, 
pdr.BOOK,

MAX(CASE WHEN (pdr.FISCAL_YEAR =2014 AND pdr.ACCOUNTING_PERIOD =11) THEN  pdr.DEPR END) as CURRENT_AMT,
MAX(CASE WHEN (pdr.FISCAL_YEAR =2104 AND pdr.ACCOUNTING_PERIOD =10) THEN pdr.DEPR  END) as PRIOR_AMT

FROM PS_ASSET pa

INNER JOIN PS_DEPR_RPT pdr 
ON pa.ASSET_ID = pdr.ASSET_ID
AND pa.BUSINESS_UNIT = pdr.BUSINESS_UNIT

WHERE 
pa.BUSINESS_UNIT=A0465
AND pdr.BOOK='PERFORM'
AND ((pdr.FISCAL_YEAR=2014 AND pdr.ACCOUNTING_PERIOD=11) 
OR (pdr.FISCAL_YEAR=2014 AND pdr.ACCOUNTING_PERIOD=10))

group by
pa.business_unit,
pa.descr,
pdr.deptid,
pdr.asset_id,
pdr.account_ad,
pdr.book

order by
pdr.asset_id

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~

SQL#2

select
asset_id
account,
journal_id,
journal_date

from ps_dist_ln 

where
book = 'PERFORM'
and business_unit = 'A0465'
and fiscal_year = 2014
and accounting_period = 11
and distribution_type = 'DE'

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~

1 个答案:

答案 0 :(得分:0)

您不需要子查询,只需加入附加表格。

SELECT 
    pa.BUSINESS_UNIT, 
    pa.DESCR,
    pdr.DEPTID, 
    pdr.ASSET_ID, 
    pdr.ACCOUNT_AD, 
    pdr.BOOK,

    MAX(CASE WHEN (pdr.FISCAL_YEAR =2014 AND pdr.ACCOUNTING_PERIOD =11) THEN  pdr.DEPR END) as CURRENT_AMT,
    MAX(CASE WHEN (pdr.FISCAL_YEAR =2104 AND pdr.ACCOUNTING_PERIOD =10) THEN pdr.DEPR  END) as PRIOR_AMT,

    pdl.journal_id,
    pdl.journal_date

FROM PS_ASSET pa

INNER JOIN PS_DEPR_RPT pdr 
    ON pa.ASSET_ID = pdr.ASSET_ID
    AND pa.BUSINESS_UNIT = pdr.BUSINESS_UNIT

LEFT JOIN ps_dist_ln pdl
    ON pdl.ASSET_ID = pdr.ASSET_ID
    AND pdl.book = pdr.book
    AND pdl.fiscal_year = pdr.fiscal_year
    AND pdl.accounting_period = pdr.accounting_period

WHERE 
    pa.BUSINESS_UNIT=A0465
    AND pdr.BOOK='PERFORM'
    AND ((pdr.FISCAL_YEAR=2014 AND pdr.ACCOUNTING_PERIOD=11) 
        OR (pdr.FISCAL_YEAR=2014 AND pdr.ACCOUNTING_PERIOD=10))
    and pdl.business_unit = 'A0465'
    and pdl.distribution_type = 'DE'

group by
    pa.business_unit,
    pa.descr,
    pdr.deptid,
    pdr.asset_id,
    pdr.account_ad,
    pdr.book

order by
    pdr.asset_id