我正在尝试计算每个帐户的数据集中每条记录之间的日期差异。
以下是我的数据
id aid value
1 1 2015-01-01
2 1 2015-01-07
4 1 2015-01-08
6 1 2015-04-10
3 2 2015-02-01
5 2 2015-02-05
我首先需要将数据合并到TIMESTAMPDIFF
以计算天数差异(即TIMESTAMPDIFF(DAY, previousValue, currentValue)
)。
如何将数据集中的行组合起来看起来像这样
aid currentValue previousValue
1 2015-01-07 2015-01-01
1 2015-01-08 2015-01-07
1 2015-04-10 2015-01-08
2 2015-02-05 2015-02-01
从那里我可以很容易地计算当前值和之前值之间的天数差异。
请注意,我有一个大型数据集,我无法在我的选择中使用子查询,这就是为什么我需要知道如何使用变量来实现它。
如何将我的初始数据集转换为第二个数据集,其中我有每个帐户的currentValue,previousValue?
这是使用上面的数据生成表的SQL
CREATE TEMPORARY TABLE lst
(
id int,
account_id int,
value date
);
INSERT INTO lst VALUES
(1, 1, '2015-01-01')
, (2, 1, '2015-01-07')
, (3, 2, '2015-02-01')
, (4, 1, '2015-01-08')
, (5, 2, '2015-02-05')
, (6, 1, '2015-04-10');
CREATE TEMPORARY TABLE lst1 AS
SELECT * FROM lst ORDER BY account_id, value ASC;
已更新
这是我在尝试Giorgos Betsos'回答如下
'1', '2015-01-01', '2015-01-07'
'1', '2015-01-07', '2015-01-08'
'1', '2015-02-05', '2015-04-10'
'2', '2015-01-08', '2015-02-01'
'2', '2015-02-01', '2015-02-05'
答案 0 :(得分:2)
MySQL 5.6架构设置:
CREATE TABLE test
(
id int,
account_id int,
value date
);
INSERT INTO test VALUES
(1, 1, '2015-01-01')
, (2, 1, '2015-01-07')
, (3, 2, '2015-02-01')
, (4, 1, '2015-01-08')
, (5, 2, '2015-02-05')
, (6, 1, '2015-04-10');
查询1 :
SELECT
IF(@accId = account_id, @prevDate, '-') as "Previous Date",
(@prevDate := value) as "Date",
(@accId :=account_id) as account_id
FROM
test, (SELECT @accId := 0) a, (SELECT @prevDate := '-') b
ORDER BY account_id ASC, value ASC
Results :
| Previous Date | Date | account_id |
|---------------|------------|------------|
| - | 2015-01-01 | 1 |
| 2015-01-01 | 2015-01-07 | 1 |
| 2015-01-07 | 2015-01-08 | 1 |
| 2015-01-08 | 2015-04-10 | 1 |
| - | 2015-02-01 | 2 |
| 2015-02-01 | 2015-02-05 | 2 |