简体   繁体   中英

How to Reference a Subquery in the Select Clause of a SQL statement

I have a SQL query that looks like this:

DECLARE @I int

SET @I = (SELECT W.PMon FROM WHouse.dbo.Rundate AS W)

SELECT L.ACCOUNT, 
L.ID,
L.OPENDATE, 
L.ORIGINALBALANCE, 
L.BALANCE, 
L.DUEDATE,
(SELECT N.BIRTHDATE FROM Sym.dbo.NAME AS N WHERE N.Account = L.Account and  N.ORDINAL = 0) AS 'PBD',
(SELECT N.BIRTHDATE FROM Sym.dbo.LOANNAME AS N WHERE L.Account = N.Account and L.ID = N.PARENTID and N.TYPE IN (01, 16, 20, 21)) AS 'JBD',
L.CREDITSCORE

FROM Sym.dbo.Loan AS L
JOIN Sym.dbo.Account AS A
ON L.Account = A.Account
WHERE L.TYPE IN (0, 1, 2, 3, 14, 15, 23) and L.BALANCE > 0 and L.CHARGEOFFDATE IS NULL and L.CLOSEDATE IS NULL and A.TYPE <> 5

In the WHERE clause, how do I reference the subqueries in the SELECT clause to do comparisons?

You can only put subqueries directly in the select clause if they return a single value. If you want to reference the columns in the sub queries in expressions in both the select clause and in where clause, you need to put the subqueries in the From clause, with aliases... or as joined tables, with the conditions in an On clause:

Just put the subquery in a join in the From clause instead.

SELECT L.ACCOUNT, L.ID,L.OPENDATE, 
    L.ORIGINALBALANCE, L.BALANCE, 
    L.DUEDATE, L.CREDITSCORE,
    pbd.Birthdate PBDBirthdate,
    jbd.Birthdate JBDBirthdate
FROM Sym.dbo.Loan AS L
   JOIN Sym.dbo.Account AS A
      ON A.Account = L.Account
   Join Sym.dbo.NAME pbd
      On pbd.Account = L.Account 
         and pbd.ORDINAL = 0
    Join Sym.dbo.LOANNAME jbd
      On jbd.Account = L.Account 
         and jbd.PARENTID = L.ID
         and jbd.TYPE IN (01, 16, 20, 21)       
WHERE L.TYPE IN (0, 1, 2, 3, 14, 15, 23) 
    and L.BALANCE > 0
    and L.CHARGEOFFDATE IS NULL  

Now you can reference any columns in those two tables using aliases pbf and/or jbd in the Select clause expressions any way you might need to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM