これはあなたの期待する結果と一致すると思います:
select "user", "contact", "barcode", "date", "in", "out","dif"
, sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
select "user", "contact", "barcode", "date", "in", "out","dif"
, lag(dif,1) over(partition by "user", "contact" order by "date" ASC) prevdif
, row_number() over(partition by "user", "contact" order by "date" DESC) rn
from "table1"
where date_trunc('day', "date") <= '2017-06-25' ::date - ( interval '1 week')::interval
and "date" > '2017-06-25'::date - ( interval '2 weeks')::interval
) d
where rn in (1,2) and prevdif is not null
order by 1,2,4 DESC
結果:
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
| | user | contact | barcode | date | in | out | dif | sum |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
| 1 | USER2 | Guillermo Tole | 987654 | 16.06.2017 05:27:00 | 500 | 420 | 80 | 170 |
| 2 | USER2 | Guillermo Tole | 281460 | 15.06.2017 05:36:00 | 310 | 220 | 90 | 170 |
| 3 | USER3 | Juan Rulfo | 123456 | 15.06.2017 05:37:00 | 450 | 300 | 150 | 150 |
| 4 | USER3 | Pepito Marquez | 346234 | 15.06.2017 05:37:00 | 600 | 360 | 240 | 240 |
+----+-------+----------------+---------+---------------------+-----+-----+-----+-----+
参照: http://rextester.com/ISHS42170
「最新」などの条件の場合、ROW_NUMBER()OVER()を使用すると、各「最新」イベントの行全体を返すことができるため、最も便利であることがわかります。これは、MAX()を使用する場合はそれほど単純ではありません。 GROUPBY。 「個別の」結果は、関数によって返される値1の行をフィルタリングすることによって返されます。
+編集
where rn in (1,2)
を使用する代わりに 次のように、OVER(PARTITION BY ...)条件でバーコードを使用する方がよいと思います。
select "user", "contact", "barcode", "date", "in", "out","dif"
, sum("in"-"out") over(partition by "user", "contact") as "sum"
from (
select "user", "contact", "barcode", "date", "in", "out","dif"
, lag(dif,1) over(partition by "user", "contact", "barcode" order by "date" ASC) prevdif
, row_number() over(partition by "user", "contact", "barcode" order by "date" DESC) rn
from "table1"
where date_trunc('day', "date") <= '2017-06-25' ::date - ( interval '1 week')::interval
and "date" > '2017-06-25'::date - ( interval '2 weeks')::interval
) d
where rn = 1 and prevdif is not null
order by 1,2,4 DESC