回答編集履歴

2

調整

2018/11/28 05:51

投稿

yambejp
yambejp

スコア116468

test CHANGED
@@ -33,3 +33,15 @@
33
33
 
34
34
 
35
35
  ```
36
+
37
+
38
+
39
+ - unionしない別解
40
+
41
+ ```SQL
42
+
43
+ select id,status,(select case when status is null then 1 else count(*) end from tbl where status=t1.status) as cnt from tbl as t1
44
+
45
+ where not exists (select 1 from tbl where t1.id>id and t1.status=status)
46
+
47
+ ```

1

参考

2018/11/28 05:51

投稿

yambejp
yambejp

スコア116468

test CHANGED
@@ -1 +1,35 @@
1
1
  そもそもstatusでgroup byしてidを表示することはできませんよ
2
+
3
+
4
+
5
+ # sample
6
+
7
+
8
+
9
+ ```SQL
10
+
11
+ create table tbl(id int,status int null);
12
+
13
+ insert into tbl values(1,1000),(2,1000),(3,2000),(4,2000),(5,null),(6,null),(7,3000);
14
+
15
+ ```
16
+
17
+
18
+
19
+ - 集計
20
+
21
+ ```SQL
22
+
23
+ select * from(
24
+
25
+ select min(id) as id,status,count(*) as cnt from tbl where status is not null group by status
26
+
27
+ union all select id,status,1 from tbl where status is null
28
+
29
+ ) as t
30
+
31
+ order by id
32
+
33
+
34
+
35
+ ```