需要帮助只选择所有孩子关闭日期的案例

时间:2013-01-05 19:06:27

标签: sql sql-server tsql

我知道标题令人困惑,但我需要帮助确定哪些法庭案件让所有与该案件相关的子女都有一个programClosureDate。 我可以运行此查询:

CaseInfo Table
CaseID,
CaseNumber,
CaseName

CaseChild Table
CaseID,           FK to CaseInfo
ChildPartyID, FK to PartyID in Party table
ProgramClosureDate

Party Table
ID,
PartyID,
Firstname,
LastName

SELECT           ci.CaseNumber, ci.CaseName, p.firstname+' '+p.lastname AS child, 
                 ci.programClosureDate
FROM             CaseInfo ci JOIN
                 CaseChild cc ON ci.CaseID = cc.CaseID JOIN
                 Party p ON cc.ChildPartyID = p.PartyID

WHERE            cc.ProgramClosureDate IS NOT NULL                    
ORDER BY         ci.CaseName

但这只是给了我那些programClosureDate IS NOT NULL的孩子 任何帮助是极大的赞赏。 安迪

3 个答案:

答案 0 :(得分:0)

您可以使用此WHERE条件

Where CaseID not in (Select CaseID  from CaseChild ProgramClosureDate IS NULL )

答案 1 :(得分:0)

此查询可以帮助您了解所有孩子都有截止日期的情况。

select CaseId
from CaseChild cc
group by CaseId
having count(*) = count(cc.ProgramClosureDate)

它正在使用一个小技巧。 。 。 count(*)是每种情况下的记录数,count(cc.ProgramCLosureDate)是非NULL关闭日期的数量。当所有案件都关闭时,这些都是相同的。

如果您想了解更多信息,可以加入:

select ci.CaseNumber, ci.CaseName, p.firstname+' '+p.lastname AS child, 
       ci.programClosureDate
from (select CaseId
      from CaseChild cc
      group by CaseId
      having count(*) = count(cc.ProgramClosureDate)
     ) closed join
     CaseInfo ci
     on closed.CaseId = ci.CaseId join
     Party p
     ON cc.ChildPartyID = p.PartyID
order by ci.CaseName

上面的子查询用于定义查询其余部分的填充。

答案 2 :(得分:0)

另一种方法...... 我不确定所建议的不同方法的性能,最好测试。

;WITH OpenCases AS
(
    SELECT DISTINCT CaseID
    FROM CaseChild
    WHERE ProgramClosureDate IS NULL
)
SELECT   ci.CaseNumber
        ,ci.CaseName
        ,child  = p.firstname+' '+p.lastname
        ,ci.programClosureDate
FROM CaseInfo   ci 
JOIN CaseChild  cc  ON ci.CaseID = cc.CaseID
JOIN OpenCases  oc  ON ci.CaseID != oc.CaseID
JOIN Party      p   ON cc.ChildPartyID = p.PartyID
WHERE cc.ProgramClosureDate IS NOT NULL                    
ORDER BY ci.CaseName