POSTGRES Group by / Inner Join

时间:2015-03-24 21:41:38

标签: sql postgresql join group-by

我在编写查询时遇到问题,以总结OD矩阵表中的数字行程。我仍然不习惯使用MS Access以外的数据库,所以请原谅我的经验不足。 SMGZ是具有区域数量的表格,matrix_od是矩阵表,具有从区域到区域的所有OD对(4109 * 4109)以及行程类型的总数。我不确定这是编写此查询的最佳方式。所以我需要做的是通过OD总结4种类型的旅行(LHDT,MHDT,HHDT,HDT_Tota)。非常感谢帮助。

SELECT 
   smgz.smg_zone AS "O_ID",
   smgz.x AS "O_X",
   smgz.y AS "O_Y",
   smgz1.smg_zone AS "D_ID",
   smgz1.x AS "D_X",
   smgz1.y AS "D_Y",
   SUM(matrix_od."LHDT") AS "LHDT_Tot", 
   SUM(matrix_od."MHDT") AS "MHDT_Tot", 
   SUM(matrix_od."HHDT") AS "HHDT_Tot", 
   SUM(matrix_od."TOT_HDT") AS "HDT_Tot"
FROM 
   public.smgz, 
   public.matrix_od, 
   public.smgz smgz1
GROUP BY
  "O_ID","O_X","O_Y","D_ID","D_X","D_Y"
INNER JOIN 
  smgz on matrix_od.O_ID = smgz.ID
INNER JOIN 
  smgz1 on matrix_od.D_ID = smgz1.ID;


 ERROR:  syntax error at or near "INNER"
 LINE 18: INNER JOIN 
          ^

********** Error **********

 ERROR: syntax error at or near "INNER"
 SQL state: 42601
 Character: 414

2 个答案:

答案 0 :(得分:1)

如注释中所述,两个主要错误是group by子句位于错误的位置,它应该在连接之后,并且您正在混合隐式连接(from子句中的多个表)和显式连接(使用join关键字)。解决方法是更改​​此部分:

FROM 
   public.smgz, 
   public.matrix_od, 
   public.smgz smgz1
GROUP BY
  "O_ID","O_X","O_Y","D_ID","D_X","D_Y"
INNER JOIN 
  smgz on matrix_od.O_ID = smgz.ID
INNER JOIN 
  smgz1 on matrix_od.D_ID = smgz1.ID;

到此:

FROM 
  public.matrix_od
INNER JOIN 
  public.smgz on matrix_od.O_ID = smgz.ID
INNER JOIN 
  public.smgz smgz1 on matrix_od.D_ID = smgz1.ID
GROUP BY
  "O_ID","O_X","O_Y","D_ID","D_X","D_Y";

答案 1 :(得分:0)

这就是诀窍!谢谢@a_horse_with_no_name& @Lamak。

 SELECT
  smgz.smg_zone AS "O_ID",
  smgz.x AS "O_X",
  smgz.y AS "O_Y",
  smgz1.smg_zone AS "O_ID",
  smgz1.x AS "D_X",
  smgz1.y AS "D_Y",     
  SUM(matrix_od."LHDT") AS "LHDT_Tot", 
  SUM(matrix_od."MHDT") AS "MHDT_Tot", 
  SUM(matrix_od."HHDT") AS "HHDT_Tot", 
  SUM(matrix_od."TOT_HDT") AS "HDT_Tot"
FROM 
  public.matrix_od 
INNER JOIN 
  smgz on matrix_od."O_ID" = smgz."id"
INNER JOIN 
  public.smgz smgz1 on matrix_od."D_ID" = smgz1."id"
GROUP BY
  smgz.smg_zone,smgz.x,smgz.y,smgz1.smg_zone,smgz1.x,smgz1.y;