我有两个表,table1
和 table2
我想将两个表与 id
联系起来,方法是将信息分组到一个相同的答案中。
表 1 :
╔════╦══════════════╦
║ id ║ product_id ║
╠════╬══════════════╬
║ 1 ║ 123 ║
║ 2 ║ 456 ║
║ 3 ║ 789 ║
╚════╩══════════════╩
表 2 :
╔════╦══════════════╦══════════════╦
║ 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 ║
╚════╩══════════════╩══════════════╩══════════════╩
我怎么能得到这个结果?
最佳答案
你可以做条件聚合来透视 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
关于sql - 自定义 SQL 响应(JOIN TABLE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59971729/