Postgres查询问题

时间:2015-07-03 04:24:55

标签: sql postgresql

db模式以及示例数据是这样的 -

(国家/地区表)

| Country | Country Code | 
--------------------------
    ABC         A 
    BCD         B

(TransactionTable)

| SrcCountryCode | DestCountryCode| SrcCurrency| DestCurrency | SrcAmount | DestAmount |
----------------------------------------------------------------------------------------
         A                B              X            Y           200         1000
         A                B              X            Y           300         1500
         B                A              Y            X           1000         200

我希望结果集像这样 -

| Corridor | Total Src Amount| Total Dest Amount | Src Currency |
-----------------------------------------------------------------
  ABC-BCD          500              200                 X
  BCD-ABC         1000              2500                Y  

我对如何映射国家/地区组合以及随后在一个表格中映射目的地和来源的总金额感到迷茫。 帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

像这样的SQL查询

select 
    d.Country+'-'+e.Country as Corridor, 
    TotalSrcAmount, 
    TotalDestAmount, 
    SrcCurrency
from TransactionTable a

join
(
    select SrcCurrency ,sum(SrcAmount) 'TotalSrcAmount'
    from TransactionTable 
    Group by SrcCurrency 
)b on a.SrcCurrency =b.SrcCurrency 

join
(
    select DestCurrency,sum(DestAmount) 'TotalDestAmount'
    from TransactionTable
    Group by DestCurrency
)c on a.SrcCurrency =c.DestCurrency

join Countrytable d on d.Country_Code=a.SrcCountryCode

join Countrytable e on e.Country_Code=a.DestCountryCode

group by 
    d.country,
    e.country,
    a.SrcCurrency