Question

I am trying to take the results of this query and return the same results except do a lookup to another table to get a value in place of my BK values.

SELECT 
Case when S.SCENARIO_SK is null then -2
when DS.SCENARIO_SK is null then -1
else DS.SCENARIO_SK
end SCENARIO_SK,

GLP.DATE_SK,

CASE
WHEN S.Q_ACCT_STR = GLEM.Q_ACCT_STR
THEN
GLA.ACCOUNT_BK
ELSE
LEFT(S.Q_ACCT_STR,5)
END ACCOUNT,

CASE
WHEN S.Q_ACCT_STR = GLEM.Q_ACCT_STR
THEN
GLO.ORG_BK
ELSE
RIGHT(S.Q_ACCT_STR,5)
END ORG,

S.Q_ACCT_STR,
S.GL_PER_AMT,
S.GL_PER_BAL,
S.Q_YTD_AMT,
S.DM_CREATE_DATE,
S.DM_AUDIT_KEY

FROM STG_GL_SUMMARY S
LEFT OUTER JOIN GL_PER_PARMS GLP ON GLP.GLP_AUTO_KEY = S.GLP_AUTO_KEY
LEFT OUTER JOIN D_GL_SCENARIO DS ON DS.SCENARIO_SK =S.SCENARIO_SK
LEFT OUTER JOIN STG_GL_EXCEPTION_MAP GLEM ON GLEM.Q_ACCT_STR = S.Q_ACCT_STR
LEFT OUTER JOIN D_GL_ACCOUNT GLA ON GLA.ACCOUNT_BK = GLEM.ACCOUNT_BK
LEFT OUTER JOIN D_GL_ORG GLO ON GLO.ORG_BK = GLEM.ORG_BK

From the above query, I would like to perform the following:

SELECT GLA.ACCOUNT_SK
FROM D_GL_ACCOUNT GLA
WHERE QUERY(ACCOUNT) = GLA.ACCOUNT.BK

SELECT GLO.ORG_SK
FROM D_GL_ORG GLO
WHERE QUERY(ACCOUNT) = GLO.ORG.BK

My final result will be all fields from both queries.

Thank you. I am relatively new to T_SQL.

No correct solution

OTHER TIPS

You may use what is called a derived table. Simply wrap the inner query with braces, assign an alias and perform a select to this. Example:

select
    tmp.value
from
    (select
        some_value as value
    from
        some_table
    ) tmp
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top