使用第二个表外键从第3个表中获取计数(*)

时间:2013-06-20 23:31:29

标签: sql sql-server-2008 tsql

我正在尝试使用第二个表外键tbl_RUR_Enclosures从第三个表tbl_RUR_RepurchaseDemands获取计数(*)。

抱歉这是错误的,我给出了错误的SQL查询。更新的一个是*

更新

select [loan number] as LoanNum, [Finding ID] as FindingID, 
       [Finding Topic], [Finding Narrative], [Reps Breached],  T.*,
     (select COUNT(*) from dbo.tbl_RUR_Enclosures where 
        tbl_RUR_Enclosures.[Finding ID]=tbl_RUR_RepurchaseDemands.
        [Finding ID]) 
     from dbo.tbl_RUR_RepurchaseDemands as RR join  
     [tbl_DefectFindingEnclosuresMateriality] as T on 
     T.[AP_ID] = RR.[AP_ID] where [loan number] in 
     (select [Loan Number] from tbl_RUR_Comprehensive 
       where Shelf = 'CWABS' and Series='2004-K' and Batch=1 
       and [Loan Number]='41090261' ) order by [Loan Number]

抛出错误Msg 4104, Level 16, State 1, Line 2 The multi-part identifier "tbl_RUR_RepurchaseDemands.Finding ID" could not be bound.

帮帮我

1 个答案:

答案 0 :(得分:2)

格式化查询确实难以理解这些问题:

select [loan num] ,[Finding ID] as FindingID,
       (select COUNT(*)
        from dbo.tbl_RUR_RepurchaseDemands
        where [Finding ID]=tbl_RUR_Comprehensive.[Finding ID]
       )
from dbo.tbl_RUR_Enclosures
where [loan num] in (select [Loan Number]
                     from tbl_RUR_Comprehensive 
                     where Shelf = 'CWABS' and Series='2004-K' and Batch=1)
order by [loan num]

您在select语句中有相关查询。但是,相关性是where子句中的子查询。这是不允许的。即使它是,子查询也不会返回您要求的列。

我认为这是一个简单的错误,因为select表明该列位于from子句的表中。如果是这样,您可以将其修复为:

select [loan num] ,[Finding ID] as FindingID,
       (select COUNT(*)
        from dbo.tbl_RUR_RepurchaseDemands
        where tbl_RUR_RepurchaseDemands.[Finding ID] = tbl_RUR_Enclosures.[Finding ID]
       )
from dbo.tbl_RUR_Enclosures
where [loan num] in (select [Loan Number]
                     from tbl_RUR_Comprehensive 
                     where Shelf = 'CWABS' and Series='2004-K' and Batch=1)
order by [loan num];