加入聚合到非聚合数据

时间:2017-07-21 17:29:16

标签: postgresql

我有以下两个表

Key          |Clicks |Impressions|
-------------+-------+-----------+
USA-SIM-CARDS|55667  |544343     |


     Key          |Conversions |State|
 -----------------+------------+------
 USA-SIM-CARDS    | 456        |NJ
 USA-SIM-CARDS    |2           |FL
 USA-SIM-CARDS    |56          |AK
 USA-SIM-CARDS    |23          |MY

我想要以下输出

     Key          |Conversions |Clicks |Impressions|
 -----------------+------------+- -----+-----------+
 USA-SIM-CARDS    | 537        |  55667|544343 

是否可以通过连接实现此目的,或者我是否必须求助于循环数据?

非常感谢。

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT f.key, f.clicks, f.impressions, sum( s.Conversions) As Conversions
FROM first_table f
JOIN second_table s
-- also LEFT JOIN can be used if you want to get rows from F 
-- even when there are no any corresponding rows in S
ON f.Key = s.Key
Group By f.key, f.clicks, f.impressions

演示:http://sqlfiddle.com/#!15/7864e/2