0
は先週からの最新のデータのみを取得するいくつかの列を合計し、私は、DATと実際の結果と予想を例に作られたいくつかの列先週、過去先週からの最新のデータのみを取得し、
を合計します。
--Taking an example kind of like this..
-- user contact barcode date in out dif
-- 1 USER2 Guillermo Tole 987654 16.06.2017 05:27:00 500 420 80
-- 2 USER2 Guillermo Tole 281460 15.06.2017 05:36:00 310 220 90
-- 3 USER2 Guillermo Tole 987654 13.06.2017 05:27:00 400 380 20
-- 4 USER2 Guillermo Tole 281460 12.06.2017 05:26:00 230 190 40
-- 5 USER3 Juan Rulfo 123456 15.06.2017 05:37:00 450 300 150
-- 6 USER3 Juan Rulfo 123456 12.06.2017 05:37:00 450 300 150
-- 7 USER3 Pepito Marquez 346234 15.06.2017 05:37:00 600 360 240
-- 8 USER3 Pepito Marquez 346234 14.06.2017 05:37:00 450 300 150
これは、このクエリを使用して、私の実際の結果です。
最初。テーブルを作成し、情報
with tabla as (
SELECT distinct on(barcode) barcode as barcode, id, date
from table1 as tabla
where date_trunc('day', date) <= '2017-06-25' ::date - (interval '1 week')::interval
and date > '2017-06-25'::date - (interval '2 weeks')::interval
order by barcode, date desc
)
はその後、内側使用してクエリを作成したいIDを保つこれは私が以前のクエリを使用して取得した結果である
select user, contact, t1.barcode, t1.date, "in", out, dif , sum("in" - out) over (partition by contact order by t1.barcode)
from table1 t1
inner join tabla on tabla.id = t1.id
where date_trunc('day', t1.date) <= '2017-06-25' ::date - (interval '1 week')::interval
and t1.date > '2017-06-25'::date - (interval '2 weeks')::interval
order by contact, barcode, date desc
-- PD, "in" is a reserved word, i have to keep it with commas
以前に作成したテーブルに参加します。
-- user contact barcode date in out sum
-- 1 USER2 Guillermo Tole 987654 16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2 USER2 Guillermo Tole 281460 15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5 USER3 Juan Rulfo 123456 15.06.2017 05:37:00 450 300 150
-- 7 USER3 Pepito Marquez 346234 15.06.2017 05:37:00 600 360 240
これは予想される結果であり、時には2週間前からのデータは存在しないだろうし、その場合には、それがnullであるか、今週空にすることができ、先週からのデータで、これもできますか(先週から)反逆が起こる。
-- | 2 weeks ago-----------------| | last week ------------------|
-- user contact barcode date in out sum date in out sum
-- 1 USER2 Guillermo Tole 987654 8.06.2017 05:27:00 500 420 170 15.06.2017 05:27:00 600 550 100
-- 2 USER2 Guillermo Tole 281460 6.06.2017 05:36:00 310 220 170 16.06.2017 05:27:00 400 350 100
-- 5 USER3 Juan Rulfo 123456 9.06.2017 05:37:00 450 300 150 14.06.2017 05:27:00 650 350 300
-- 7 USER3 Pepito Marquez 346234 7.06.2017 05:37:00 600 360 240 15.06.2017 05:27:00 750 500 250
おかげで、はい、それは他の質問から続けている、私は本当に、感謝します今私はいくつかの観察を行4が間違っていると思った、両方の日付は同じ週の行2で、先週からのデータがあり、2および3週間前のデータを表示しています..行3は3週の前に、それは左の "列" –