在主 - 详细信息方案中从sql数据库表中选择多个记录

时间:2010-05-29 09:48:25

标签: sql master-pages

我在主 - 细节关系中有两个表。 结构或多或少如下: 主表:

MasterID, DetailID, date, ...
masterID1, detailID1, 2010/5/1, ....
masterID2, detailID1, 2008/6/14, ...
masterID3, detailID1, 2009/5/25, ...
masterID4, detailID2, 2008/7/24, ...
masterID5, detailID2, 2010/4/1, ...
masterID6, detailID4, 2008/9/16, ...

详情表:

DetailID, ...
detailID1, ...
detailID2, ...
detailID3, ...
detailID4, ...

我需要从详细信息表中获取所有记录以及主表中的最后一条记录(最后一个主表中的日期)。 像这样:

detailID1, masterID1, 2010/5/1, ....
detailID2, masterID5, 2010/4/1, ...
detailID3, null, null, ...
detailID4, masterID6, 2008/9/16, ...

我不知道该怎么做。 有谁能够帮我? 非常感谢。 扬

1 个答案:

答案 0 :(得分:1)

Select ....
From Details As D
    Left Join   (
                Select M1.MasterId, M.DetailId, M.Date...
                From Master As M1
                Where MasterId  = (
                                    Select Max(M2.MasterId)
                                    From Master As M2
                                    Where M2.DetailId = M1.DetailId
                                    Group By M2.DetailId
                                    Having Max(M2.Date) = M1.Date
                                    )
                ) As M
        On M.DetailId = D.DetailId

我在这里做的是处理关系。如果你有两个具有相同DetailId和Date的Master行,我选择的MasterId最高。

顺便说一下,如果您有公用表表达式(CTE),这个问题会非常简单。使用CTE,您可以执行以下操作:

With LastMasterRows As
                (
                Select MasterId, DetailId, Date
                    , Row_Number() Over( Partition By DetailId Order By Date, MasterId ) As ItemRank
                From Master
                )
Select ...
From Details As D
    Left Join LastMasterRows As M
        On M.DetailId = D.DetailId
            And M.ItemRank = 1