加入查询问题 - 连接附近的语法错误

时间:2016-07-15 10:36:52

标签: sql postgresql join

   TRADERS                                            INCENTIVE
   __________________________________________      _____________
   TRDID  NAME  SUPERVISOR  LOCATION   PAY         TRDID  INCENTIVE
   ------------------------------------------      -------------
  66  Chad                 NY         110000        17    5000
  17  Yena          66     TN          75000        21    2000
   5  Karam         66     TN          80000         66    5000
  21  Rose           5     HI         100000      ...


 --group by highest pay for location and traderid                                               

                   select e.trdid trdid, e.location, max (e.pay+ coalesce(b.incentive, 0))  maxtotal  from traders e
                        join incentive b on e.trdid = b.trdid
                            group by e.location, trdid
                   join (                       
                   (select e.trdid trdid, max (e.pay+ coalesce(b.incentive, 0))  maxtotal  from traders e
                join incentive b on e.trdid = b.trdid
               group by e.location, e.trdid)) using (trdid)

当我尝试加入表及其子查询时出现错误。 我在PostgreSQL中尝试这个

我试图在每个地点只获得收入最高的交易者,基于薪酬和奖励的排名作为总支付。我想要打印    交易员姓名,薪酬,激励和总薪酬(薪酬加激励)。

请问您的查询有什么问题吗?我在连接

附近收到错误说明语法错误

2 个答案:

答案 0 :(得分:0)

你真的不能这样做:

select .... from ....
 join ... on ....
group by ....
 join ....

如果要加入两个聚合子查询,请使用公用表表达式(with子句)。更好的方法是尝试进行设置操作,然后在最后进行聚合。

答案 1 :(得分:0)

这是您的查询,格式化:

select e.trdid trdid, e.location, max (e.pay+ coalesce(b.incentive, 0))  maxtotal
from traders e join incentive
     b
     on e.trdid = b.trdid
group by e.location, trdid join
     ((select e.trdid trdid, max (e.pay+ coalesce(b.incentive, 0)) as maxtotal
       from traders e join
            incentive b
            on e.trdid = b.trdid
       group by e.location, e.trdid
     ))
     using (trdid)

您似乎误解了SQL语法。 JOIN是仅在FROM子句中理解的运算符。 GROUP BY是一个单独的条款。在 FROM子句之后。我想你打算:

select e.trdid trdid, e.location, max(e.pay + coalesce(b.incentive, 0))  maxtotal
from traders e join
     incentive b
     on e.trdid = b.trdid join
     (select e.trdid trdid, max(e.pay+ coalesce(b.incentive, 0)) as maxtotal
      from traders e join
           incentive b
           on e.trdid = b.trdid
      group by e.location, e.trdid
     ) b
     using (trdid)
group by e.location, trdid;

您可能会注意到我格式化了我的查询,因此SQL子句在左侧对齐。这就是为什么FROMGROUP BY位于左侧,而JOIN不是。

但是,我认为编写查询的一种更简单的方法是:

select distinct on (e.trdid) e.trdid as trdid, e.location,
       max(e.pay + coalesce(b.incentive, 0)) as maxtotal
from traders e join
     incentive b
     on e.trdid = b.trdid
group by e.trdid, e.location
order by e.trdid, maxtotal desc