回答編集履歴

2

調整

2018/12/05 05:25

投稿

yambejp
yambejp

スコア114784

test CHANGED
@@ -27,3 +27,55 @@
27
27
  group by sale_date
28
28
 
29
29
  ```
30
+
31
+
32
+
33
+ # idごと
34
+
35
+
36
+
37
+ ```SQL
38
+
39
+ create table tbl(id int,sale_date date,discount_price int);
40
+
41
+ insert into tbl values
42
+
43
+ (1,'2018-11-02',2390),
44
+
45
+ (1,'2018-11-02',510),
46
+
47
+ (1,'2017-10-22',5280),
48
+
49
+ (2,'2016-04-04',4608),
50
+
51
+ (2,'2018-10-12',2200);
52
+
53
+ ```
54
+
55
+
56
+
57
+ - 集計1
58
+
59
+ ```SQL
60
+
61
+ select id,sale_date,sum(discount_price) from tbl
62
+
63
+ group by id,sale_date
64
+
65
+ having (id,sale_date) in (select id,max(sale_date) from tbl group by id)
66
+
67
+ ```
68
+
69
+
70
+
71
+ - 集計2
72
+
73
+ ```SQL
74
+
75
+ select id,sale_date,sum(discount_price) from tbl as t1
76
+
77
+ where not exists(select 1 from tbl where t1.id=id and t1.sale_date<sale_date)
78
+
79
+ group by id,sale_date
80
+
81
+ ```

1

tuiki

2018/12/05 05:25

投稿

yambejp
yambejp

スコア114784

test CHANGED
@@ -9,3 +9,21 @@
9
9
  having sale_date=(select max(sale_date) from tbl)
10
10
 
11
11
  ```
12
+
13
+ # 追記
14
+
15
+
16
+
17
+ 絞ってから集計
18
+
19
+
20
+
21
+ ```SQL
22
+
23
+ select sale_date,sum(discount_price) from tbl as t1
24
+
25
+ where not exists(select 1 from tbl where t1.sale_date<sale_date)
26
+
27
+ group by sale_date
28
+
29
+ ```