質問編集履歴

1

質問自体の修正

2023/06/13 00:31

投稿

person
person

スコア224

test CHANGED
File without changes
test CHANGED
@@ -1,44 +1,57 @@
1
1
  下記テーブルを作成し、データをインサートします。
2
2
  ```
3
3
  CREATE TABLE table1(id integer);
4
+ CREATE TABLE table2 (id integer, pcs integer, category integer);
4
- CREATE TABLE table2(id integer, pcs integer);
5
+ CREATE TABLE table1(id integer, value text);
5
6
 
6
7
  INSERT INTO table1(1);
7
8
  INSERT INTO table1(2);
8
9
 
9
- INSERT INTO table2(1, 10);
10
+ INSERT INTO table2 VALUES(1, 10, 1);
10
- INSERT INTO table2(1, 5);
11
+ INSERT INTO table2 VALUES(1, 9, 1);
12
+ INSERT INTO table2 VALUES(1, 8, 2);
13
+ INSERT INTO table2 VALUES(1, 7, 2);
11
- INSERT INTO table2(2, 3);
14
+ INSERT INTO table2 VALUES(2, 6, 1);
15
+ INSERT INTO table2 VALUES(2, 5, 1);
12
- INSERT INTO table2(2, -2);
16
+ INSERT INTO table2 VALUES(2, 4, 2);
17
+ INSERT INTO table2 VALUES(2, 3, 2);
18
+
19
+ INSERT INTO table3 VALUES(1, 'a');
20
+ INSERT INTO table3 VALUES(1, 'b');
13
21
  ```
14
22
 
15
23
  これを各idごとにpcsの合計値を表示したいです。
16
- (これ以外にidをキーとしていくつかテーブルを結合することを想定しています
24
+ ただしcategory が1のののみ
17
25
 
18
26
  作ったSELECT文
19
27
  ```
20
- SELECT table1.id, SUM(table2.pcs) FROM table1
28
+ SELECT table1.id, SUM(table2.pcs), table3.value
29
+ FROM table1
21
30
  LEFT JOIN table2
22
31
  ON table1.id = table2.id
32
+ AND table2.category = 1
33
+ GROUP BY table1.id
34
+ LEFT JOIN table3
35
+ ON table1.id = table3.id
23
36
  ```
24
37
 
25
38
  エラー
26
39
  ```
27
- ERROR: column "table1.id" must appear in the GROUP BY clause or be used in an aggregate function
28
- LINE 1: SELECT table1.id, SUM(table2.pcs) FROM table1
40
+ ERROR: syntax error at or near "LEFT"
41
+ LINE 7: LEFT JOIN table3
42
+ ^
43
+ SQL 状態: 42601
44
+ 文字: 146
29
45
  ```
30
-
31
- GROUP BY を使うように言われているのですが、
32
- JOINに対してどのように使えばよいか分かりません。
33
46
 
34
47
  回答よろしくお願いします。
35
48
 
36
49
  期待値
37
50
  ```
38
- id, sum
51
+ id, pcs, value
39
- ---------
52
+ --------------
40
- 1, 15
53
+ 1, 19, a
41
- 2, 1
54
+ 2, 11, b
42
55
  ```
43
56
 
44
57
  psql (PostgreSQL) 14.1