如何获得第一行和最后一个表行之间的差异?

时间:2019-01-11 13:11:26

标签: sql-server datetime

我有下表:

ID  val  DateTime  
1   20   2018-12-11 14:57:20.620   
2   30   2018-12-11 20:57:20.940
3   15   2018-12-12 00:57:20.460
4   41   2018-12-12 04:57:20.830
5   22   2018-12-12 11:57:20.077

此外,我有以下存储过程:

ALTER PROCEDURE [dbo].[C_PS_PS]
 -- Add the parameters for the stored procedure here
 @DataStart datetime=null,
 @DataStop  datetime=null
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
SELECT [ID]
      ,[val]
      ,[DateTime]
  FROM [DB].[dbo].[C_Tbl]
  WHERE DateTime between @DataStart and @DataStop
END

execute [C_PS_PS] '2018-12-11 14:57:20.620','2018-12-12 11:57:20.077'

当我执行它时,我得到上表。我的问题是:如何根据valDataStart得到第一行和最后一行之间的DataStop差异?

为了举例说明我想要的,假设我要获取日期为2018-12-11 20:57:20.9402018-12-12 04:57:20.830的记录的val差异。

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作。 cte带来最早的日期及其val,而cte2带来最新的日期及其val。然后最后使用cross join并从cte.val中减去cte2.val(反之亦然):

;with cte as
(
    select top 1 [DateTime], val from [dbo].[C_Tbl] 
    WHERE [DateTime] between @DataStart and @DataStop
    order by [DateTime] asc
),
cte2 as
(
    select top 1 [DateTime], val from [dbo].[C_Tbl] 
    WHERE [DateTime] between @DataStart and @DataStop
    order by [DateTime] desc
)
select  
cte.[DateTime], cte2.[DateTime], cte.val, cte2.val,
--DATEDIFF( dd , cte.[DateTime], cte2.[DateTime]) 'difference_days' 
cte.val-cte2.val
from cte cross join cte2

答案 1 :(得分:0)

尝试以下操作:

ALTER PROCEDURE [dbo].[C_PS_PS]
 -- Add the parameters for the stored procedure here
 @DataStart datetime=null,
 @DataStop  datetime=null
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
;WITH VALUES_START_END AS
(
    SELECT TOP 1 VAL FROM C_Tbl WHERE [DateTime] = @DataStart
    UNION 
    SELECT TOP 1 -VAL FROM C_Tbl WHERE [DateTime] = @DataStop
)

SELECT [ID]
      ,[val]
      ,[DateTime]
      ,ABS(T.VAL_DIFF_BETWEEN_SART_END)VAL_DIFF_BETWEEN_SART_END
  FROM [C_Tbl]
  CROSS APPLY (SELECT SUM(VAL) VAL_DIFF_BETWEEN_SART_END FROM VALUES_START_END)T
  WHERE DateTime between @DataStart and @DataStop
END
GO

enter image description here