如何获得第一个和最后一个记录

时间:2014-04-02 20:56:12

标签: sql tsql sql-server-2012

一次。我的目标是控制一组必须以22 CodeId(GO)开头并以23 CodeId(STOP)结束的数据。有时数据可以像示例一样。因此,我必须检查第一条记录,看看是否是CodeId = 23然后删除此记录,如果CodeId = 22则删除最后一条记录然后删除记录。 timedate var是有序的。

DATE                DriverId CodeId
**2014/03/01 13:50:00, 7168,     23     -- STOP**
2014/03/01 14:00:00, 7168,     22     -- GO
2014/03/01 14:30:00, 7168,     23     -- STOP
2014/03/01 14:40:00, 7168,     22     -- GO
2014/03/01 16:10:00, 7168,     23     -- STOP
2014/03/01 16:50:00, 7168,     22     -- GO
2014/03/01 17:20:00, 7168,     23     -- STOP
2014/03/01 18:30:00, 7168,     22     -- GO
2014/03/01 19:10:00, 7168,     23     -- STOP
**2014/03/01 19:20:00, 7168,     22     -- GO**

我写了这段代码

IF (SELECT TOP(1) CodeId FROM #tbl) = 23
BEGIN
   DELETE ... (Dont know what to do)
END

IF (SELECT TOP(1) CodeId FROM #tbl ORDER BY DATE DESC) = 22
BEGIN
   DELETE ... (Dont know what to do)
END

我不知道DELETE声明,你能帮我吗?如果你认为我必须以不同的方式解决这个问题,请告诉我如何解决。先感谢您。

我正在使用MS SQL Server 2012

2 个答案:

答案 0 :(得分:2)

;With CTE
AS (
    SELECT [DATE],DriverId, CodeId,
          , ROW_NUMBER() OVER (ORDER BY [DATE] ASC) rn_Stop
          , ROW_NUMBER() OVER (ORDER BY [DATE] DESC) rn_Go
    FROM Table_Name
   )
DELETE FROM CTE
WHERE 
      (rn_Stop = 1 AND CodeId = 23)
OR  
      (rn_Go   = 1 AND CodeId = 22)

答案 1 :(得分:0)

我认为此代码可以帮助您:

IF CURSOR_STATUS('global','cur_test')=1
        CLOSE cur_test

    IF CURSOR_STATUS('global','cur_test')=-1
        DEALLOCATE cur_test;

    DECLARE  @v_DriverId INT
            ,@v_CodeId INT

    DECLARE cur_test CURSOR FOR
    SELECT DriverId, CodeId
    FROM #tbl 
    ORDER BY DATE DESC



    OPEN cur_test   
    FETCH NEXT FROM cur_test INTO @v_DriverId, @v_CodeId
    WHILE @@FETCH_STATUS = 0   
    BEGIN   

            IF (@v_CodeId = 22)
            BEGIN
                --GO....Do this ...Do that...@v_DriverId
            END


            IF (@v_CodeId = 23)
            BEGIN
                --STOP....Do this ...Do that...@v_DriverId
            END


        FETCH NEXT FROM cur_test INTO @v_DriverId, @v_CodeId
    END   

    CLOSE cur_test   
    DEALLOCATE cur_test

祝你好运:)