【问题标题】:Joining Tables in PostgreSQL在 PostgreSQL 中连接表
【发布时间】:2021-02-07 16:57:28
【问题描述】:

我无法使用 PostgreSQL 从多个表中将数据放入一个表中。我有以下两个表:

schedule.event:

 | starttime  | endtime    | hash |
 | 1612716238 | 1612716266 | xyz  |
 | 1612716912 | 1612718972 | abc  |

schedule.resource:

 | name     | type      | hash |
 | sat1     | satellite | xyz  |
 | station1 | station   | xyz  |
 | modem1   | modem     | xyz  |
 | sat2     | satellite | abc  |
 | station1 | station   | abc  |
 | modem1   | modem     | abc  | 

我想获取如下表格格式的数据:

 | starttime  | endtime    | satellite | station  | modem  |
 | 1612716238 | 1612716266 | sat1      | station1 | modem1 |
 | 1612716912 | 1612718972 | sat2      | station1 | modem1 |
 

我在编写 PostgreSql 查询来执行此操作时遇到问题。

谢谢

【问题讨论】:

    标签: sql postgresql join


    【解决方案1】:

    你需要条件聚合如下:

    Select t1.starttime, t1.endtime, t1.hash,
           Max(case when t2.type = 'satelite' then name end) as satelite,
           Max(case when t2.type = 'station' then name end) as station,
           Max(case when t2.type = 'modem' then name end) as modem
      From event t1
      Join resource t2 on t1.hash = t2.hash
      Group by t1.starttime, t1.endtime, t1.hash;
    

    【讨论】:

    • 或者:max(name) filter (where t2.type = 'satellite')
    • 是的,这也是一个不错的选择,但我想使用标准 sql 给出答案。感谢@a_horse_with_no_name 添加替代方法/synatx。
    • @Popeye 。 . . FILTER标准 SQL。
    猜你喜欢
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2020-09-13
    • 2017-07-07
    • 2014-11-18
    相关资源
    最近更新 更多