遍历SQL中的数据

问题描述

具有此数据集:https://www.db-fiddle.com/f/6vmgx4krsgMRgprDjErdqu/0

我想增加一列,以显示到条目之前的时间距离,我该如何实现?

非常感谢您:)

解决方法

正如您在小提琴中所说的那样,您使用MySQL 5,7

您必须使用用户定义的变量。

我选择了TIMEDIFF来显示差异,因为您没有说明所需的信息,所以我选择了它,但是由于您同时拥有这两个值,因此可以使用不同的mysql函数

模式(MySQL v5.7)

pip install diskcache==4.1.0 

查询#1

CREATE TABLE `someTable` (
    `ID` INT,`POS` INT,`Date` DATETIME,`Customer` VARCHAR(64)
);

INSERT INTO `someTable` VALUES 
(1,10,"2017-03-10 08:00:00","Peter"),(2,11,"2017-03-10 08:00:01",(3,12,"2017-03-10 08:00:04",(4,17,"2017-03-10 08:00:05",(5,16,"2017-03-10 08:00:08","Karl"),(6,"2017-03-10 08:00:09",(7,"2017-03-10 08:00:12",(8,"2017-03-10 08:00:13","Peter");

SELECT * FROM someTable

View on DB Fiddle

,

如果您正在运行MySQL 8.0,只需使用lag()timetstampdiff()。假设您希望日期差异与同一customer的“上一个”记录相同,并且应以秒为单位:

select
    t.*,timestampdiff(
        second,lag(date,1,date) over(partition by customer order by date),date
    ) diff_seconds
from sometable t

每组的第一条记录相差0秒。

如果您运行的是早期版本,那么我建议您使用相关子查询。尽管它的效率可能比用户变量低一些,但它更安全,并且可以面向未来(计划在将来的MySQL版本中删除用户变量):

select 
    t.*,coalesce((select max(t1.date) from sometable t1 where t1.customer = t.customer and t1.date < t.date),date),date
    ) diff_seconds
from sometable t

有关示例数据,both queries return

| ID  | POS | Date                | Customer | diff_seconds |
| --- | --- | ------------------- | -------- | ------------ |
| 1   | 10  | 2017-03-10 08:00:00 | Peter    | 0            |
| 2   | 11  | 2017-03-10 08:00:01 | Peter    | 1            |
| 3   | 12  | 2017-03-10 08:00:04 | Peter    | 3            |
| 4   | 17  | 2017-03-10 08:00:05 | Peter    | 1            |
| 5   | 16  | 2017-03-10 08:00:08 | Karl     | 0            |
| 6   | 17  | 2017-03-10 08:00:09 | Karl     | 1            |
| 7   | 10  | 2017-03-10 08:00:12 | Peter    | 7            |
| 8   | 10  | 2017-03-10 08:00:13 | Peter    | 1            |
,

类似这样的事情可以做到:

insert into @temp ([ID],[Date])
select
    t.[ID],datediff(day,Lag(t.[Date]) over(order by t.[Date]),t.[Date]) as [DateDiffFromPrevRow]
from someTable t

select
    t.[ID],t.[POS],t.[Date],t.[Customer],temp.[DateDiffFromPrevRow]
from sometable t
join @temp temp on temp.[ID] = t.[ID]