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

回答編集履歴

2

調整

2018/12/05 05:25

投稿

yambejp
yambejp

スコア117892

answer CHANGED
@@ -12,4 +12,30 @@
12
12
  select sale_date,sum(discount_price) from tbl as t1
13
13
  where not exists(select 1 from tbl where t1.sale_date<sale_date)
14
14
  group by sale_date
15
+ ```
16
+
17
+ # idごと
18
+
19
+ ```SQL
20
+ create table tbl(id int,sale_date date,discount_price int);
21
+ insert into tbl values
22
+ (1,'2018-11-02',2390),
23
+ (1,'2018-11-02',510),
24
+ (1,'2017-10-22',5280),
25
+ (2,'2016-04-04',4608),
26
+ (2,'2018-10-12',2200);
27
+ ```
28
+
29
+ - 集計1
30
+ ```SQL
31
+ select id,sale_date,sum(discount_price) from tbl
32
+ group by id,sale_date
33
+ having (id,sale_date) in (select id,max(sale_date) from tbl group by id)
34
+ ```
35
+
36
+ - 集計2
37
+ ```SQL
38
+ select id,sale_date,sum(discount_price) from tbl as t1
39
+ where not exists(select 1 from tbl where t1.id=id and t1.sale_date<sale_date)
40
+ group by id,sale_date
15
41
  ```

1

tuiki

2018/12/05 05:25

投稿

yambejp
yambejp

スコア117892

answer CHANGED
@@ -3,4 +3,13 @@
3
3
  select sale_date,sum(discount_price) from tbl
4
4
  group by sale_date
5
5
  having sale_date=(select max(sale_date) from tbl)
6
+ ```
7
+ # 追記
8
+
9
+ 絞ってから集計
10
+
11
+ ```SQL
12
+ select sale_date,sum(discount_price) from tbl as t1
13
+ where not exists(select 1 from tbl where t1.sale_date<sale_date)
14
+ group by sale_date
6
15
  ```