我想使用 1 个表创建一个使用 2 组查询的新表。
测试代码:http://sqlfiddle.com/#!9/02e3ff/5
引用表:
所需表:
它们共享相同的 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
关于MySQL:两次使用同一个表创建新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649320/