试图弄清楚如何在SQL中构建查询

时间:2012-06-28 23:08:37

标签: sql-server-2008 tsql

我在构建查询时遇到一些问题我需要从FamilyAccountDetails表中返回AccountID,其中Family帐户至少有一个子项(一个子项是AccountDetails.AccountID等于FamilyAccountDetails.AccountID的子项),它具有HoldFlag = 0.

AccountDetails
EntID  |HoldFlag|AccountID|StatusFlag

FamilyAccountDetails
EntID|FamilyAccountID|AccountID|StatusFlag

SQL:

      Select FD.AccountID, FD.FamilyAccountId 
from Test2TMAdvisor5.dbo.FamilyAccountDetails FD
      where FD.EnterpriseId = 'TestDan'
      and AccountId in (Select AccountId from Test2TMAdvisor5.dbo.AccountDetails AD where Ad.AccountID = FD.AccountId and ad.HoldFlag =0)

2 个答案:

答案 0 :(得分:1)

SELECT
    FD.[AccountID]
    ,FD.[FamilyAccountId] 
FROM
    FamilyAccountDetails FD
WHERE
    FD.[EnterpriseId] = 'TestDan'
    AND EXISTS 
        (
        SELECT 
            * 
        FROM 
            AccountDetails AD
        WHERE 
            AD.[AccountID] = FD.[AccountId] 
            AND AD.[HoldFlag] = 0
        )

答案 1 :(得分:0)

此SQL查询应提取所需的结果:

SELECT
    FD.[AccountID]
    ,FD.[FamilyAccountId] 
FROM
    FamilyAccountDetails FD
INNER JOIN AccountDetails AD on AD.[AccountID] = FD.[AccountId] 
WHERE
    FD.EntID = 'TestDan'
    AND AD.[HoldFlag] = 0