我在查找表格时遇到问题,我使用postgresql作为我的数据库
我有2张表A和表B如下
table A
---------------------------------------------------------------
| headerid | amount | depart | arrival |
---------------------------------------------------------------
| 100 | 10 | australia | german |
| 101 | 30 | german | australia |
| 102 | 25 | australia | german |
| 103 | 20 | irak | iran |
table B
---------------------
| headerid | name |
---------------------
| 100 | a |
| 100 | b |
| 101 | c |
| 102 | d |
| 103 | e |
我需要的结果是
| depart | arrival | total amount| name |
-------------------------------------------------------------
| australia | german | 35 | d |
| german | australia | 30 | c |
| irak | iran | 20 | e |
我到目前为止已经尝试过查询
答案 0 :(得分:0)
我真的不了解底层逻辑,但这个查询会产生你想要的东西:
SELECT depart, arrival, sum(amount) "total amount" , max(b1.name) "name" FROM a
JOIN (
SELECT headerid, max(name) "name" FROM b
GROUP BY headerid
) b1
ON a.headerid = b1.headerid
GROUP BY depart, arrival
ORDER BY depart
输出:
| DEPART | ARRIVAL | TOTAL AMOUNT | NAME |
|-----------|-----------|--------------|------|
| Australia | German | 35 | d |
| German | Australia | 30 | c |
| irak | iran | 20 | e |
小提琴here。