質問編集履歴

2

SQLを具体的に例示してみました。分かりやすくなっているといいな。。

2016/03/22 08:06

投稿

commabee
commabee

スコア38

test CHANGED
File without changes
test CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  1つの購入履歴テーブルに複数のマスターをJoinしているのですが、
10
10
 
11
- マスターは年月で歴管理しているデータで膨大な件数とします。
11
+ マスターは年月で歴管理しているデータで膨大な件数とします。
12
12
 
13
13
 
14
14
 
@@ -22,70 +22,68 @@
22
22
 
23
23
  ###変更元のSQL
24
24
 
25
+ 購入履歴テーブル:利用者ID、購入年月日、金額
26
+
27
+ 支払方法マスター:利用者ID、支払方法、有効開始年月、有効終了年月 ※年月でユニークになる
28
+
29
+ お届け先マスター:利用者ID、住所、有効開始年月、有効終了年月 ※年月でユニークになる
30
+
31
+
32
+
25
- ※例なのでテーブル名に意味はありません。シンプルな構成にてあります。
33
+ いView:利用者ID、購入年月、金額合計、支払方法、住所
34
+
35
+
26
36
 
27
37
  ```SQL
28
38
 
29
- --ザマスタ対象年月で絞り込
39
+ --購入履歴テブル利用者と年月で絞り込んで合計を算出
30
40
 
31
- with master_user@ as (
41
+ with 購入履歴@ as (
32
42
 
33
- select * from master_user
43
+ select 利用者ID, sum(金額) from 購入履歴
34
44
 
45
+ where to_char(購入年月日, 'yyyy/mm') = {yyyy/mm} ←画面から入力された年月
46
+
47
+ and 利用者ID in ('xxx,xxx,xxx,xxx,xxx') ←画面から入力された複数のユーザID
48
+
49
+ group by 利用者ID, to_char(購入年月日, 'yyyy/mm')
50
+
51
+ ),
52
+
53
+ --支払方法マスターを利用者と年月で絞り込む
54
+
55
+ 支払方法@ as (
56
+
57
+ select * from 支払方法
58
+
35
- where {yyyy/mm} between master_user.from and master_user.to
59
+ where {yyyy/mm} between 有効開始年月 and 有効終了年月 ←画面から入力された年月
60
+
61
+ and 利用者ID in ('xxx,xxx,xxx,xxx,xxx') ←画面から入力された複数のユーザID
36
62
 
37
63
  ),
38
64
 
39
- --住所マスタを対象年月で絞り込
65
+ --お届け先マスタ利用者と年月で絞り込
40
66
 
41
- master_zip@ as (
67
+ お届け先@ as (
42
68
 
43
- select * from master_zip
69
+ select * from お届け先
44
70
 
45
- where {yyyy/mm} between master_zip.from and master_zip.to
71
+ where {yyyy/mm} between 有効開始年月 and 有効終了年月 ←画面から入力された年月
46
72
 
47
- ),
48
-
49
- --購入履歴テーブルを対象年月で集計
50
-
51
- table1@ as (
52
-
53
- select userid, zipcd from table1
54
-
55
- where to_char(date1, 'yyyy/mm') = {yyyy/mm}
73
+ and 利用者ID in ('xxx,xxx,xxx,xxx,xxx') ←画面から入力された複数のユーザID
56
-
57
- group by userid, zipcd
58
74
 
59
75
  )
60
76
 
61
-
62
-
63
77
  --それぞれのテーブルをJoinでつなぐ
64
78
 
65
- select * from table1@
79
+ select * from 購入履歴@
66
80
 
67
- left join master_user@
81
+ left join 支払方法@
68
82
 
69
- on table1.userid = master_user@.userid
83
+ on 購入履歴.利用者ID = 支払方法@.利用者ID
70
84
 
71
- left join master_zip@
85
+ left join お届け先@
72
86
 
73
- on table2.zipcd = master_zip@.zipcd
87
+ on 購入履歴.利用者ID = お届け先@.利用者ID
74
88
 
75
89
  ```
76
-
77
-
78
-
79
- ちなみに以下のようなViewだと凄く遅くなりました
80
-
81
- ```SQL
82
-
83
- select * from table1
84
-
85
- left join master_user
86
-
87
- on table1.userid = master_user.userid
88
-
89
- and to_char(date1, 'yyyy/mm') between master_user.from and master_user.to
90
-
91
- ```

1

悪い例のSQLを修正しました{yyyy/mm}→to_char\(date1, 'yyyy/mm'\)

2016/03/22 08:06

投稿

commabee
commabee

スコア38

test CHANGED
File without changes
test CHANGED
@@ -86,6 +86,6 @@
86
86
 
87
87
  on table1.userid = master_user.userid
88
88
 
89
- and {yyyy/mm} between master_user.from and master_user.to
89
+ and to_char(date1, 'yyyy/mm') between master_user.from and master_user.to
90
90
 
91
91
  ```