停止LAG功能递增

时间:2017-07-28 19:04:16

标签: sql-server

我希望我的输出看起来像这样。

有什么方法可以使用Lag函数来做到这一点吗?

ID1     Column1 

NULL      NULL 
NULL      NULL 
2017      2017
NULL      2017
NULL      2017
NULL      2017
NULL      2017 
NULL      NULL 
NULL      NULL     
2048      2048
NULL      2048
NULL      2048
2098      2098
NULL      2098
NULL      2098
NULL      2098

2 个答案:

答案 0 :(得分:2)

我假设您尝试使用IGNORE NULLS模拟SELECT ID ,Column1 ,0 + LEFT(MAX(ID_Column1) OVER (ORDER BY ID),10) AS LagID ,0 + RIGHT(MAX(ID_Column1) OVER (ORDER BY ID),10) AS LagColumn1 FROM @Table t CROSS APPLY (VALUES (FORMAT(ID,'D10') + FORMAT(Column1,'D10'))) V(ID_Column1);

在这种情况下,您所需的结果不正确。

你可以做(​​demo - borrows scsimon's data

@RequestMapping(value = "/login")
public ModelAndView getLoginForm(ModelAndView model) throws IOException {
    model.addObject("user",new User());
    model.setViewName("login_form");
    return model;
}

@RequestMapping(value = "/loginUser", method = RequestMethod.POST)
public ModelAndView login(@ModelAttribute User user) {
    User loggedInUser=userService.getUser(user.getEmail(),user.getPassword());
        if(loggedInUser==null) {
            ModelAndView model=new ModelAndView("redirect:/login");
            model.addObject("errorMessage","Invalid Login");
            return model;
        }
    return new ModelAndView("redirect:/users");
}

答案 1 :(得分:0)

嗯,您需要另一个显示订单的列...否则LEADLAG可能会失去同步。话虽如此,你需要查看所有以前的无界限行,直到你点击NULL,这是一个带子查询的简单方法

declare @table table (ID int identity(1,1), Column1 int)
insert into @table
values
(NULL),
(NULL),
(2017),
(NULL),
(NULL),
(NULL),
(2048),
(NULL),
(NULL),
(NULL),
(NULL),
(2098)


SELECT
    ID
    ,Column1
    ,ISNULL(Column1, (SELECT TOP 1 Column1 FROM @Table WHERE ID < t.ID AND Column1 IS NOT NULL ORDER BY ID DESC)) as Column2
FROM
    @Table t

<强>返回

+----+---------+---------+
| ID | Column1 | Column2 |
+----+---------+---------+
|  1 | NULL    | NULL    |
|  2 | NULL    | NULL    |
|  3 | 2017    | 2017    |
|  4 | NULL    | 2017    |
|  5 | NULL    | 2017    |
|  6 | NULL    | 2017    |
|  7 | 2048    | 2048    |
|  8 | NULL    | 2048    |
|  9 | NULL    | 2048    |
| 10 | NULL    | 2048    |
| 11 | NULL    | 2048    |
| 12 | 2098    | 2098    |
+----+---------+---------+