我有一个如下所示的SQL查询:
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
在WHERE子句中,如何引用SELECT子句中的子查询进行比较?
答案 0 :(得分:2)
如果子查询返回单个值,则只能将子查询直接放在select子句中。如果要在select子句和where子句中的表达式中的子查询中引用 列 ,则需要将子查询放在From子句中,并带有别名...或作为连接表,具有On子句中的条件:
只需将子查询放在From子句中的连接中即可。
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
现在,您可以使用Select子句表达式中的别名pbf和/或jbd来引用这两个表中的任何列。