从具有相同日期的列中减去的存储过程

Stored procedure to subtract from column with same dates

我有以下列:

2022-05-25T17:31:34+0000    92  7   1
2022-05-25T16:06:46+0000    50  5   9
2022-05-25T13:05:27+0000    91  10  106
2022-05-25T09:17:01+0000    48  4   4
2022-05-25T08:43:05+0000    60  4   2
2022-05-25T06:26:38+0000    24  3   6
2022-05-24T15:14:49+0000    55  12  6
2022-05-24T12:25:35+0000    43  8   2
2022-05-24T11:15:24+0000    66  7   2
2022-05-24T10:45:56+0000    37  15  2
2022-05-23T17:51:09+0000    59  7   1
2022-05-23T17:50:44+0000    47  6   3
2022-05-23T15:48:02+0000    126 7   13
2022-05-23T11:42:26+0000    64  9   9
2022-05-27T06:00:29+0000    3   0   1
2022-05-25T17:31:34+0000    96  7   1
2022-05-25T16:06:46+0000    55  5   9
2022-05-25T13:05:27+0000    99  11  116
2022-05-25T09:17:01+0000    52  4   15
2022-05-25T08:43:05+0000    61  4   2
2022-05-25T06:26:38+0000    26  3   6
2022-05-24T15:14:49+0000    57  13  7
2022-05-24T12:25:35+0000    43  8   2
2022-05-24T11:15:24+0000    66  7   2
2022-05-24T10:45:56+0000    38  15  2
2022-05-23T17:51:09+0000    59  7   1
2022-05-23T17:50:44+0000    47  6   3
2022-05-23T15:48:02+0000    127 7   13

如果您查看第 16 行,它的日期与第一行相同,但 PostLikes 的数量不同(92 和 96),PostComments 和 PostShares 也会发生变化。我想创建一个存储过程,当我输入日期时它会 return 差异。例如,如果我 select 日期为 2022-05-25T13:05:27+0000 的第三行,它应该给出结果:

DateT                           PostLikes        PostComments        PostShares
2022-05-25T13:05:27+0000            7                  1                 10

现在这样做的一种方法是:

select max(PostLikes) - min(PostLikes) as LikeDifference, max(PostComments) - min(PostComments) as CommentDifference, max(PostShares) - min(PostShares) as ShareDifference
from kpitb.userLikes
where DateT =  "2022-05-25T17:31:34+0000";

但是这种方法只适用于有两个值的情况,数据库将有多个具有相同日期的值。 (注意 DateT 是 VARCHAR) 例如

Row 1  2022-05-25T13:05:27+0000     24
Row 2  2022-05-25T13:05:27+0000     34
Row 3  2022-05-25T13:05:27+0000     67

如何找出差异。

如有任何帮助,我们将不胜感激。

使用 window 函数,您可以找到最大 ID 和以前的值,主查询变得微不足道。

with cte as
(select t.*,
         lag(postlikes) over(partition by datet order by id) prevlikes,
         lag(postcomments) over(partition by datet order by id) prevcomments,
         lag(postshares) over(partition by datet order by id) prevshares,
         t1.maxid
from t
join (select max(id) maxid,datet from t group by datet) t1 on t1.datet = t.datet
order by datet,id
) 
select datet,
         case when prevlikes is null then postlikes else postlikes - prevlikes end likes,
       case when prevcomments is null then postcomments else postcomments - prevcomments end comments,
       case when prevshares is null then postshares else postshares - prevshares end shares
from cte
where  id = maxid;

https://dev.mysql.com/doc/refman/8.0/en/window-functions.html