sql - 自定义 SQL 响应(JOIN TABLE)

标签 sql database join group-by pivot

我有两个表,table1table2
我想将两个表与 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      ║
╚════╩══════════════╩══════════════╩══════════════╩

我怎么能得到这个结果?

最佳答案

你可以做条件聚合来透视 table2table1 :

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/

相关文章:

mysql - 建立正确的数据导入顺序,防止FK冲突

mysql - couchdb 相当于关系数据库模型

mysql - 在 MySQL 查询中左连接还是右连接?

java - SQLite登录授权失败

database - Biztalk 暂停数据库中的消息

mysql - Mysql中如何根据参数自动创建uuid触发器?

mysql - 在 WHERE 中加入 MAX

java - hql join 无法解析属性;使用两个表映射

sql - 将日期显示为 YYYY-MMM 的函数

sql - 使用 SQL IN 和 SQL OR 运算符的 Rails 3 ActiveRecord 查询