将ISNULL函数与LEAD函数一起使用:遇到麻烦

时间:2019-04-29 08:44:51

标签: sql sql-server tsql window-functions

我在组合LEAD和ISNULL函数时遇到麻烦。基本查询如下:

DECLARE @ReportTimeStart DATETIME = '2019-04-25 06:50'
DECLARE @ReportTimeEnd DATETIME = '2019-04-25 23:59';

SELECT
    [tbl_tg_machinestate_ndx],
    [Machine_State],
    [t_stamp],
    LEAD([t_stamp]) OVER (ORDER BY [tbl_tg_machinestate_ndx]) NextStateTime
FROM [db_SPE_Carrig].[dbo].[tbl_TG_MachineState]
WHERE [t_stamp] BETWEEN @ReportTimeStart AND @ReportTimeEnd

这给了我很长的清单:

tbl_tg_machinestate_ndx    Machine_State    t_stamp                    NextStateTime
5893                       130              2019-04-25 23:44:49.160    2019-04-25 23:46:34.670
5894                       170              2019-04-25 23:46:34.670    2019-04-25 23:50:01.370
5895                       100              2019-04-25 23:50:01.370    NULL

我想使用ISNULL()函数将最后的NULL值替换为报告的结束时间。像这样:

SELECT
    [tbl_tg_machinestate_ndx],
    [Machine_State],
    [t_stamp],
    ISNULL(
    (LEAD([t_stamp]) OVER (ORDER BY [tbl_tg_machinestate_ndx]) NextStateTime),
    @ReportTimeEnd)
  FROM [db_SPE_Carrig].[dbo].[tbl_TG_MachineState]
  WHERE [t_stamp] BETWEEN @ReportTimeStart AND @ReportTimeEnd

但是不幸的是,这不起作用。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

LEAD函数接受一个“默认”值,该值穿过窗口的末端时将返回。像这样使用它:

SELECT
    [tbl_tg_machinestate_ndx],
    [Machine_State],
    [t_stamp],
    LEAD([t_stamp], 1, @ReportTimeEnd) OVER (ORDER BY [tbl_tg_machinestate_ndx]) AS NextStateTime
    -- ----------------^
FROM [db_SPE_Carrig].[dbo].[tbl_TG_MachineState]
WHERE [t_stamp] BETWEEN @ReportTimeStart AND @ReportTimeEnd

如果要区分最后一个值和一个空值,此方法很有用。

答案 1 :(得分:0)

尝试一下:

  SELECT
    [tbl_tg_machinestate_ndx],
    [Machine_State],
    [t_stamp],
    ISNULL(LEAD([t_stamp]) OVER (ORDER BY [tbl_tg_machinestate_ndx]),@ReportTimeEnd) NextStateTime
  FROM [db_SPE_Carrig].[dbo].[tbl_TG_MachineState]
  WHERE [t_stamp] BETWEEN @ReportTimeStart AND @ReportTimeEnd

我认为您在这里有一个sintax错误:

ISNULL(
    (LEAD([t_stamp]) OVER (ORDER BY [tbl_tg_machinestate_ndx]) NextStateTime),
    @ReportTimeEnd)