SQL where子句用于自引用表

时间:2015-08-31 08:32:41

标签: sql-server

我有类似下表的内容:

CREATE TABLE [dbo].[Test]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Title] [nvarchar](450) NULL,
    [Description] [nvarchar](4000) NULL,
    [Created] [datetime] NULL,
    [OrgId] [int] NULL CONSTRAINT [FK_Test_OrgId] FOREIGN KEY REFERENCES Test(Id),

    CONSTRAINT [PK_Test] 
       PRIMARY KEY CLUSTERED ([Id] ASC)
) 

新条目有OrgId = null。如果已编辑条目,则会创建一个新行,并将OrgId设置为其原始父级。如果多次编辑条目,则所有子项都将OrgId设置为原始行的Id。创建的日期时间提供“订单”。

我需要做的是只选择最新版本。

鉴于下表,我希望仅选择Id 3,5和& 6

Id  Title   Description          Created        PreId
-----------------------------------------------------
1   Car     Orginal car          2014-01-01     NULL
2   House   Original house       2014-01-01     NULL
3   Bike    Original bike        2014-01-01     NULL
4   Car     Car updated          2014-06-01     1
5   Car     Car updated again    2014-08-01     1
6   House   house updated        2014-09-01     2

任何意见都赞赏。

感谢。

2 个答案:

答案 0 :(得分:0)

由于所有记录都指向原始行(而不是前一行):

package demo1.web;

import demo.exceptions.SupportInfoException;

public class TestInnerException {
void testIt() throws Exception{
    try{
        int i=0;
        int j=1/i;
    }catch(Exception e){
        System.out.println("business logic .. .. . . ");
        throw e;
        // I want to excute these below line ,
         but it is unreachable because you aleready throwing the excetion ..
        //any Hacks for it ?
         System.out.println("Lines after throwing the exception ... .");

    }

    System.out.println("I want this logic to be run . . . . .");

}
public static void main(String[] args) throws SupportInfoException, Exception {
    TestInnerException t = new TestInnerException();
    t.testIt();


}
void testRunTimeEx(){
        int i=0;
        int j=1/i;

}
}

答案 1 :(得分:0)

WITH Titles AS
(
  SELECT DISTINCT Title
  FROM dbo.Test
)
SELECT A.ID, Ti.Title, A.[Description], A.Created, A.OrgId
FROM Titles AS Ti
OUTER APPLY (SELECT TOP (1) ID, [Description], [Created], [OrgId]
             FROM dbo.Test AS Te
             WHERE Te.Title = Ti.Title
             ORDER BY Created DESC
            ) AS A;