我在SQlite中有以下表格:
_id | token | status | timestamp | mood | eta | name | calc_eta __________________________________________________________________________ 168 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4154 |样本名称| 1516625533082 169 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4214 |样本名称| 1516625533108 170 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4274 |样本名称| 1516625533414 171 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4334 |样本名称| 1516625533160 172 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4394 |样本名称| 1516625533680 173 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4420 |样品名称| 1516625533068 174 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4428 |样本名称| 1516625533482 175 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4483 |样品名称| 1516625533155 176 | iqmC.3aHMBGbl | ok | 1516625084498 | 50 | -4543 |样本名称| 1516625533148 177 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2526 |样品名称| 1516632672019 178 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2520 |样品名称| 1516632671903 179 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2460 |样品名称| 1516632672321 180 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2344 |样本名称| 1516632672859 181 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2336 |样本名称| 1516632671939 182 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2281 |样本名称| 1516632672802 183 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2220 |样本名称| 1516632671828 184 | TFbintkHMBw4H | ok | 1516630122485 | 50 | 2161 |样本名称| 1516632672625
我正在尝试提出一个查询,它会给我两个最新的(基于自动增量 _id ), calc_eta 值之间的区别对于每个不同的令牌值。
所以在这种情况下结果应该是:
iqmC.3aHMBGbl | -7
TFbintkHMBw4H | 797
我使用SQL得到了这么多,但它目前没有提供每个不同令牌的计算值,我不确定如何进一步。
SELECT DISTINCT token,
(SELECT calc_eta
FROM DATA s
WHERE
(SELECT count(*)
FROM DATA f
WHERE f.token = s.token
AND f._id >= s._id) <= 1) -
(SELECT calc_eta
FROM
(SELECT calc_eta,
MIN(_id)
FROM DATA s
WHERE
(SELECT count(*)
FROM DATA f
WHERE f.token = s.token
AND f._id >= s._id) <= 2)) AS delay
FROM DATA;
答案 0 :(得分:0)
在大多数SQL方言中,您可以使用lag()
:
select d.*,
(calc_eta - prev_calc_eta) as diff
from (select d.*,
lag(calc_eta) over (partition by token order by _id) as prev_calc_eta,
row_number() over (partition by token order by _id desc) as seqnum
from data d
) d
where seqnum = 1;