2016-07-15 7 views
0
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でこれを試しています結合問合せの問題 - 結合の近くの構文エラー

私は、支払いとインセンティブの合計額を合計金額に基づいて計算することで、各地域で最も高い支払いトレーダーのみを獲得しようとしています。 トレーダー名、給与、インセンティブ、総給与(給与とインセンティブ)を印刷したいと思います。

私のクエリで何が間違っているとアドバイスできますか?私は近い

+0

私はPostgreSQLの専門家ではないけど、私はあなたが句から欠場言う:

しかし、私は、クエリを記述する方がはるかに簡単な方法があると思います – Jens

答えて

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 
0

を結合構文エラーを示すエラーを取得し、あなたが本当に行うことはできません。

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

次の2つの集計サブクエリに参加したい場合は、共通テーブル式(with句)を使用します。あなたのセット操作をして、最後に集約しようとする方がいいです。