【问题标题】:Custom SQL response (JOIN TABLE)自定义 SQL 响应(JOIN TABLE)
【发布时间】:2020-01-29 16:39:43
【问题描述】:

我有两张桌子,table1table2

我想将这两个表与id 联系起来,方法是将信息分组到一个相同的答案中。

table1

╔════╦══════════════╦
║ id ║  product_id  ║
╠════╬══════════════╬
║  1 ║      123     ║
║  2 ║      456     ║
║  3 ║      789     ║
╚════╩══════════════╩

table2

╔════╦══════════════╦══════════════╦
║ id ║    status    ║     date     ║
╠════╬══════════════╬══════════════╬
║  1 ║   received   ║    02/20     ║
║  1 ║   shipped    ║    03/20     ║
║  2 ║   received   ║    04/20     ║
║  2 ║   shipped    ║    05/20     ║
║  3 ║   received   ║    06/20     ║
║  3 ║   shipped    ║    07/20     ║
╚════╩══════════════╩══════════════╩

我想要这个输出:

╔════╦══════════════╦══════════════╦══════════════╦
║ id ║    r_date    ║   s_date     ║  product_id  ║
╠════╬══════════════╬══════════════╬══════════════╬
║  1 ║     02/20    ║    03/20     ║     123      ║
║  2 ║     04/20    ║    05/20     ║     456      ║
║  3 ║     06/20    ║    07/20     ║     789      ║
╚════╩══════════════╩══════════════╩══════════════╩

我怎样才能得到这个结果?

【问题讨论】:

    标签: sql database join group-by pivot


    【解决方案1】:

    您可以进行条件聚合以将table2 旋转到table1

    select 
        t1.id, 
        max(case when t2.status = 'received' then t2.date end) r_date,
        max(case when t2.status = 'shipped' then t2.date end) s_date,
        t1.product_id
    from table1 t1
    inner join table2 t2 on t.id = t2.id
    group by t1.id, t2.product_id
    order by t1.id
    

    【讨论】:

    • 是必需的 max(),但理论上每个 id 只有一个日期?
    • @Travis:这就是条件聚合的原理。我们需要将条件表达式包装在聚合函数中以折叠行。可以是min()max(),都无所谓。
    【解决方案2】:

    你可以使用两个LEFT JOINs,如:

    select
      a.id,
      r.date as r_date,
      s.date as s_date,
      a.product_id
    from table1 a
    left join table2 r on r.id = a.id and r.status = 'received'
    left join table2 s on s.id = a.id and s.status = 'shipped'
    

    【讨论】:

    • 非常感谢您! :)
    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 2016-09-04
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多