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

回答編集履歴

3

追記

2018/06/07 05:50

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -2,7 +2,7 @@
2
2
  ```SQL
3
3
  select AAA,CCC, SUM(cnt)
4
4
  from (
5
- select AAA,CCC,(select count(*) from テーブル where BBB=t1.BBB) cnt
5
+ select AAA,CCC,(select count(*) from テーブル where AAA=t1.AAA and BBB=t1.BBB) cnt
6
6
  from テーブル t1
7
7
  where CCC is not null
8
8
  ) iv
@@ -12,7 +12,18 @@
12
12
 
13
13
  ということなので、以下のようにするだけでも良いかも
14
14
  ```SQL
15
- select AAA,CCC,(select count(*) from テーブル where BBB=t1.BBB) cnt
15
+ select AAA,CCC,(select count(*) from テーブル where AAA=t1.AAA and BBB=t1.BBB) cnt
16
16
  from テーブル t1
17
17
  where CCC is not null
18
+ ```
19
+
20
+ 別解釈として、CCCが有効(Nullでない)なAAAとBBBのパターンの件数を求めるという事だと、
21
+ ```SQL
22
+ select AAA,CCC,(select count(*) from テーブル where AAA=V1.AAA and BBB=V1.BBB) cnt
23
+ from (
24
+ select AAA,BBB,CCC
25
+ from テーブル t1
26
+ where CCC is not null
27
+ group by AAA,BBB,CCC
28
+ ) v1
18
29
  ```

2

追記

2018/06/07 05:50

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -7,4 +7,12 @@
7
7
  where CCC is not null
8
8
  ) iv
9
9
  group by AAA,CCC
10
+ ```
11
+ > CCCはどれか一つだけ必ず値あり
12
+
13
+ ということなので、以下のようにするだけでも良いかも
14
+ ```SQL
15
+ select AAA,CCC,(select count(*) from テーブル where BBB=t1.BBB) cnt
16
+ from テーブル t1
17
+ where CCC is not null
10
18
  ```

1

訂正

2018/06/07 05:39

投稿

sazi
sazi

スコア25430

answer CHANGED
@@ -1,7 +1,10 @@
1
- 相関副問合せで件数を取得します
1
+ 相関副問合せで件数を取得しておき、それを集計します
2
2
  ```SQL
3
+ select AAA,CCC, SUM(cnt)
4
+ from (
3
- select AAA,CCC,(select count(*) from テーブル where BBB=t1.BBB)
5
+ select AAA,CCC,(select count(*) from テーブル where BBB=t1.BBB) cnt
4
- from テーブル t1
6
+ from テーブル t1
5
- where CCC is not null
7
+ where CCC is not null
8
+ ) iv
6
9
  group by AAA,CCC
7
10
  ```