質問するログイン新規登録

回答編集履歴

5

追記

2019/06/08 03:37

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -7,4 +7,49 @@
7
7
  and (select count(*) from tb where 日付>=t1.日付)<=7
8
8
  ) tc
9
9
  on ta.日付=tc.日付
10
+ ```
11
+ 追記
12
+ --
13
+ MySQL8.0は**with**や**分析関数**が使えるので利用すると簡潔になります。
14
+ MySQL8.0は手元にないのでpostgresを使用して検証しました。
15
+
16
+ キーワードとしては**with**と**lag**位ですね。
17
+ 最終的に相関副問合せを用いてますが、集計を別テーブルに分けて結合する方法もあると思います。
18
+ 現状インデックスが無いなら使い物にならないほど低速です。
19
+ また、日付と証券コードで一意になっていないのも前日比などでは問題です。
20
+ ```SQL
21
+ with
22
+ date_range as (
23
+ -- 指定した期間内(最新日付より過去7日)
24
+ select date from b hst
25
+ where date <= (select max(date) from b)
26
+ and (select count(*) from b where date>=hst.date)<=7
27
+ )
28
+ , peak as (
29
+ --期間高値:指定した期間内の最高値、最安値
30
+ select STOCK_CD, STOCK_NAME, Max(HIGH) max_peak, Min(LOW) min_peak
31
+ from a where date in (select date from date_range)
32
+ group by STOCK_CD, STOCK_NAME
33
+ )
34
+ , rasio as (
35
+ --前日比 :テーブルB内にある最新日の終値とその前営業日の終値との比較
36
+ select date, STOCK_CD
37
+ , close - lag(CLOSE) over (partition by STOCK_CD order by date) rasio
38
+ from a
39
+ )
40
+ select pk.*
41
+ --・高値日 :期間高値を付けた日
42
+ , (select max(date) from a
43
+ where STOCK_CD=pk.STOCK_CD and HIGH=pk.max_peak
44
+ and date in (select date from date_range)
45
+ )
46
+ --・安値日 :期間安値を付けた日
47
+ , (select max(date) from a
48
+ where STOCK_CD=pk.STOCK_CD and LOW=pk.min_peak
49
+ and date in (select date from date_range)
50
+ )
51
+ , (select max(rasio) from rasio
52
+ where date = (select max(date) from b) and STOCK_CD=pk.STOCK_CD
53
+ )
54
+ from peak pk
10
55
  ```

4

訂正

2019/06/08 03:37

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -2,9 +2,9 @@
2
2
  ```SQL
3
3
  select ta.*
4
4
  from ta inner join (
5
- select * from tb
5
+ select * from tb t1
6
6
  where 日付 <= date()
7
- and (select count(*) from tb where 日付>=ta.日付)<=7
7
+ and (select count(*) from tb where 日付>=t1.日付)<=7
8
8
  ) tc
9
9
  on ta.日付=tc.日付
10
10
  ```

3

訂正

2019/06/05 15:10

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -6,5 +6,5 @@
6
6
  where 日付 <= date()
7
7
  and (select count(*) from tb where 日付>=ta.日付)<=7
8
8
  ) tc
9
- on ta.日付=tb.日付
9
+ on ta.日付=tc.日付
10
10
  ```

2

推敲

2019/06/05 15:10

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -1,4 +1,4 @@
1
- 取り敢えず集計していないQSLです。
1
+ 取り敢えず集計していないSQLです。
2
2
  ```SQL
3
3
  select ta.*
4
4
  from ta inner join (

1

訂正

2019/06/05 15:09

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -1,9 +1,10 @@
1
+ 取り敢えず集計していないQSLです。
1
2
  ```SQL
2
3
  select ta.*
3
- from t1 inner join (
4
+ from ta inner join (
4
5
  select * from tb
5
6
  where 日付 <= date()
6
- and (select count(*) from tb where 日付>=tb.日付)<=7
7
+ and (select count(*) from tb where 日付>=ta.日付)<=7
7
8
  ) tc
8
9
  on ta.日付=tb.日付
9
10
  ```