SQL:选择最新子子位置

时间:2011-05-31 13:48:41

标签: sql sql-server sql-server-2005

我有一些看起来像这样的模型:父母与Child有1-2-M的关系,而Child与Sub-Child有1-2-M的关系。

Parent
------
Parent_ID


Child
-----
Child_ID,
Parent_ID


Sub-Child
---------
Child_ID,
Version_Number (numeric),
Sent (date),
Void (date)

我想要一个查询,它返回一个唯一的parent_id列表,其中相关子子的最新版本(由version_number判断)为'sent' == null,但是'void' != null

我一直在脑子里咀嚼这个,无法解决问题。

非常感谢任何建议。

谢谢,

罗伯特

5 个答案:

答案 0 :(得分:3)

这将是:

;WITH CTE_LatestSubChildren AS
(
    SELECT Parent_ID, Latest_Version_Number = max(sc.Version_Number)
    FROM
       Child c
       JOIN [Sub-Child] sc on c.Child_ID = sc.Child_ID
    GROUP BY c.Parent_ID

)
SELECT
    ParentID
FROM
    CTE_LatestSubChildren lsc
    JOIN Child c 
        on lsc.Parent_ID = c.Parent_ID
    JOIN [Sub-Child] sc 
        ON sc.Child_ID = c.Child_ID    
        AND sc.version_number = lsc.Latest_Version_Number   
        AND sc.Sent IS NULL    
        AND sc.Void IS NOT NULL

请注意,这可能需要修改,因为它未经过测试,并且不完全清楚最新版本相同的多个子记录会发生什么。

答案 1 :(得分:1)

我不是我可以测试它的地方,但听起来你需要一个子查询来提取每个孩子的最大版本号,然后自我加入以获得其余的子子信息。这样的事情就是我的想法:

SELECT DISTINCT
  Parent_ID
FROM
  Parent JOIN Child
    ON Parent.Parent_ID = Child.Parent_ID
  JOIN (
    SELECT Child_ID, MAX(Version_Number)
    FROM Sub-Child
    GROUP BY Child_ID ) AS MaxSubchild
  JOIN Sub-Child
    ON Sub-Child.Child_ID = MaxSubchild.Child_ID AND
      Sub-Child.Version_Number = MaxSubchild.Version_Number
WHERE
  SUb-Child.Sent IS NULL AND
  Sub-Child.Void IS NOT NULL;

答案 2 :(得分:0)

首先通过child_id获取最高版本:

select child_id, max(version_number) as version_number
from subchild
group by child_id

然后将其作为子查询加入子子项和子项,并应用where where条件。

答案 3 :(得分:0)

或者,如果没有子查询,请尝试

SELECT DISTINCT p.parent_id
FROM sub_children sc
  LEFT JOIN children c ON sc.parent_id = c.child_id
  LEFT JOIN parents p ON c.parent_id = p.parent_id
WHERE sc.sent == null, but sc.void != null

答案 4 :(得分:0)

您也可以使用Rank():

SELECT DISTINCT TOP 100 PERCENT ST.Parent_ID
FROM
(
    SELECT RANK() OVER (PARTITION BY C.Parent_ID ORDER BY SC.Version_Number DESC) AS [RANK], 
    C.Parent_ID, SC.Sent, SC.Void
    FROM Child C 
    INNER JOIN Sub_Child SC ON C.Child_ID = SC.Child_ID
) ST
WHERE [RANK] = 1
AND [Sent] IS NULL AND [Void] IS NOT NULL