MySQL:两次使用同一个表创建新表

标签 mysql data-structures

我想使用 1 个表创建一个使用 2 组查询的新表。

测试代码:http://sqlfiddle.com/#!9/02e3ff/5

引用表:

enter image description here

所需表:

enter image description here

它们共享相同的 order_id。
type = A, updated_at = pDate
type = B, updated_at = dDate

查询 1:

select t.order_id, t.updated_at as pDate, weekday(t.updated_at) from transactions t 
where t.type = 'A' group by t.order_id

查询 2:

select t.order_id, max(t.updated_at) as dDate, weekday(max(t.updated_at)) from transactions t 
where t.type= 'B'
group by t.order_id;

对于 type = A,我想要获取最早的 updated_at 日期,而对于 type = B,我想要获取最晚的 updated_at 日期。

目前,我尝试了联合,但他们给了我 2 行而不是所需的表。

我如何连接或联合这 2 个查询以获得所需的表?

或者,有没有更好的方法来做到这一点?谢谢!

最佳答案

你可以尝试这样的事情:

SELECT order_id, min(pDate) pDate, max(dDate) dDate FROM(
    SELECT
      order_id,
      if(type='A',updated_at,null) pDate,
      if(type='B',updated_at,null) dDate
    FROM transactions
) as d
GROUP BY order_id

SQLFiddle

关于MySQL:两次使用同一个表创建新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649320/

相关文章:

php - 向用户显示以前上传的内容以供选择

PHP从数组中插入数据到数据库中并在html表中输出数据库数据

c++ - B+树实现,** vs *

java - 如何将现有树(有 child ,但没有 parent )扩展为双向链接树?

c - ‘;’ token 之前出现错误 : expected ‘,’ , ‘)’ 或 ‘.’

php - 在字段中存储多值的最佳方法

javascript - 如何插入单选按钮的选中值,该值是来自php中另一个表的数组

MySQL查询自定义排序功能

c++ - 用于排序/检索字符串的数据结构

data-structures - 哈希中的高效模糊查找