回答編集履歴
1
サンプル追記
test
CHANGED
@@ -5,3 +5,65 @@
|
|
5
5
|
[PostgreSQLでCSVからUpdateをかける](https://qiita.com/kuwana/items/851125828a20d23cca1b)
|
6
6
|
|
7
7
|
[PostgreSQLのUPSERT方式の簡易性能比較](https://qiita.com/fujii_masao/items/6e9417f78dc0cbd0e13d)
|
8
|
+
|
9
|
+
|
10
|
+
|
11
|
+
追記
|
12
|
+
|
13
|
+
--
|
14
|
+
|
15
|
+
サンプル追記
|
16
|
+
|
17
|
+
```SQL
|
18
|
+
|
19
|
+
-- Create tmp table
|
20
|
+
|
21
|
+
create temp table tmp (id int, day date,value varchar(20)) on commit drop;
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
-- Import data from csv:
|
26
|
+
|
27
|
+
copy tmp from 'C:/test.csv' delimiter ',' csv header;
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
-- IDが重複しているもののうち最新の日付以外を削除
|
32
|
+
|
33
|
+
delete from tmp as target where day < (select max(day) from tmp where id=target.id);
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
-- Update table from tmp
|
38
|
+
|
39
|
+
update import_test_tbl set
|
40
|
+
|
41
|
+
id = tmp.id
|
42
|
+
|
43
|
+
, date = tmp.day
|
44
|
+
|
45
|
+
, value = tmp.value
|
46
|
+
|
47
|
+
from tmp
|
48
|
+
|
49
|
+
where import_test_tbl.id = tmp.id
|
50
|
+
|
51
|
+
;
|
52
|
+
|
53
|
+
-- Insert table from tmp
|
54
|
+
|
55
|
+
insert into import_test_tbl
|
56
|
+
|
57
|
+
select id, day, value
|
58
|
+
|
59
|
+
from tmp
|
60
|
+
|
61
|
+
where not exists( --キーが存在していないもの
|
62
|
+
|
63
|
+
select 1 from import_test_tbl where id = tmp.id
|
64
|
+
|
65
|
+
)
|
66
|
+
|
67
|
+
;
|
68
|
+
|
69
|
+
```
|