在与另一个表合并之前,将一个表分组为一个参数

时间:2012-04-07 19:04:04

标签: sql postgresql merge

我已经成功合并了3个表(使用ID),但是当我尝试添加第4个表时 - 输出完全混乱(值变得不现实/错误)所以我认为我与事实有关,这个第4个表有未分组的ID,所以我需要在加入这个新表之前对它们进行分组。现在查询如下:

SELECT name, SUM(money) AS MONEY
FROM transactions
JOIN results ON transactions.id = results.id
JOIN more ON results.per_id = more.per_id
GROUP BY name
HAVING SUM(money)>500

当我加入新表时:

SELECT name, SUM(money) AS MONEY, SUM(data_from_NT1), SUM(data_from_NT2)
FROM transactions
JOIN results ON transactions.id = results.id
JOIN more ON results.per_id = more.per_id

JOIN newtable ON results.per_id = newtable.per_id

GROUP BY name
HAVING SUM(money)>500

是否可以执行命令GROUP BY per_id:

(JOIN newtable ON results.per_id = newtable.per_id GROUP BY per_id)
在将此新表添加到主表之前

上面的行不起作用。

2 个答案:

答案 0 :(得分:1)

您可以将group by移动到子查询:

join   (
       select  per_id
       ,       sum(col1) as col1_avg
       ,       avg(col2) as col2_avg
       from    newtable 
       group by
               per_id
       ) as newtable
on     results.per_id = newtable.per_id

如果您对per_id进行分组,则必须汇总任何其他列。

答案 1 :(得分:1)

是的,这是可能的,但您必须将其写为SELECT。这是可能答案的第一个版本:

SELECT name,
       SUM(money)             AS money,
       SUM(nt2.data_from_NT1) AS data_from_NT1,
       SUM(nt2.data_from_NT2) AS data_from_NT2
  FROM transactions AS t
  JOIN results      AS r ON t.id = r.id
  JOIN more         AS m ON r.per_id = m.per_id
  JOIN (SELECT per_id, SUM(data_from_NT1) AS data_from_NT1, SUM(data_from_NT2) AS data_from_NT2
          FROM newtable GROUP BY per_id
       ) AS nt2 ON results.per_id = nt2.per_id
 GROUP BY name
HAVING SUM(money) > 500;

目前还不完全清楚你是否需要SUMs' SUMs'在主选择列表中;你可能不会。它还不清楚namemoney列的来源;我通常也会在它们前面添加适当的表别名。有了这些警告,这可能更接近你所追求的目标:

SELECT name, SUM(money) AS MONEY, nt2.data_from_NT1, nt2.data_from_NT2
  FROM transactions AS t
  JOIN results      AS r ON t.id = r.id
  JOIN more         AS m ON r.per_id = m.per_id
  JOIN (SELECT per_id, SUM(data_from_NT1) AS data_from_NT1, SUM(data_from_NT2) AS data_from_NT2
          FROM newtable GROUP BY per_id
       ) AS nt2 ON results.per_id = nt2.per_id
 GROUP BY name, nt2.data_from_NT1, nt2.data_from_NT2
HAVING SUM(money) > 500;

毫无疑问,还有其他方法可以写出来。主查询中的分组可能更好地放入并行子查询中,在主查询中留下简单的直接连接。但我们没有掌握实际为您做的信息。