回答編集履歴

1

抽出

2017/11/06 02:38

投稿

yambejp
yambejp

スコア114843

test CHANGED
@@ -11,3 +11,95 @@
11
11
  DEFをテーブルABそれぞれにDISTINCTで抽出してUNION ALLし
12
12
 
13
13
  group byしてhavingでcount(*)が1のデータを抽出するといいでしょう
14
+
15
+
16
+
17
+ # sample
18
+
19
+ ```SQL
20
+
21
+ create table tbl_a(id int unique ,D int,E int, F int, G varchar(10));
22
+
23
+ insert into tbl_a values(1,100,100,100,'aaa'),(2,200,200,200,'bbb'),(3,100,200,100,'ccc'),(4,100,100,100,'ddd');
24
+
25
+ create table tbl_b(id int unique ,D int,E int, F int, H varchar(10));
26
+
27
+ insert into tbl_b values(101,100,100,100,'eee'),(102,200,100,200,'fff'),(103,200,200,200,'ggg'),(104,200,100,200,'hhh');
28
+
29
+
30
+
31
+ ```
32
+
33
+ - 片方にしかないDEF
34
+
35
+ ```SQL
36
+
37
+ select D,E,F from(
38
+
39
+ select distinct D,E,F from tbl_a
40
+
41
+ union all select distinct D,E,F from tbl_b
42
+
43
+ ) as sub
44
+
45
+ group by D,E,F
46
+
47
+ having count(*)=1
48
+
49
+ ```
50
+
51
+
52
+
53
+ - それぞれ合致するデータを抽出
54
+
55
+ ```SQL
56
+
57
+ /* tbl_a */
58
+
59
+ select * from tbl_a
60
+
61
+ where (D,E,F) in (
62
+
63
+ select D,E,F from(
64
+
65
+ select distinct D,E,F from tbl_a
66
+
67
+ union all select distinct D,E,F from tbl_b
68
+
69
+ ) as sub
70
+
71
+ group by D,E,F
72
+
73
+ having count(*)=1
74
+
75
+ );
76
+
77
+
78
+
79
+ /* tbl_b */
80
+
81
+ select * from tbl_b
82
+
83
+ where (D,E,F) in (
84
+
85
+ select D,E,F from(
86
+
87
+ select distinct D,E,F from tbl_a
88
+
89
+ union all select distinct D,E,F from tbl_b
90
+
91
+ ) as sub
92
+
93
+ group by D,E,F
94
+
95
+ having count(*)=1
96
+
97
+ );
98
+
99
+ ```
100
+
101
+
102
+
103
+ ※注意:命題の追記をみるかぎり、tbl_aとtbl_bは構成が違うようなので
104
+
105
+ 一発でデータ抽出はできません。二度にわけて処理して下さい