使用外部联接联接 2 个或更多 sql 个查询

Joining 2 or more sql queries using outer join

我正在尝试使用 'outer join' 从 5 sql 语句中得到 return 结果,我想要 stock_id、stock_name 和每天的销售额总和过去 5 天 return 作为单独的列编辑。我该如何构建它?

select s1.sid as sid,s1.sname as sname, sum1,sum2,sum3,sum4,sum5
from
(
 select stock.id as sid, stock.Name as sname, sum(orders.Quantity) as 'sum1' from orders inner join stock on `Stock_id`= stock.id where  orders.Created_at Like '2020-05-16%' group by Stock_id asc
) 
as s1
full outer join
(
select stock.id as sid,stock.Name as sname, sum(orders.Quantity) as 'sum2' from orders inner join stock on `Stock_id`= stock.id where  orders.Created_at Like '2020-05-17%' group by Stock_id asc
)
as s2 on s1.sid=s2.sid 
outer join
(
select stock.id as sid,stock.Name as sname, sum(orders.Quantity) as 'sum3' from orders inner join stock on `Stock_id`= stock.id where  orders.Created_at Like '2020-05-18%' group by Stock_id asc
) as s3 on s1.sid=s3.sid 
outer join
( 
select stock.id as sid,stock.Name as sname,sum(orders.Quantity) as 'sum4' from orders inner join stock on `Stock_id`= stock.id where  orders.Created_at Like '2020-05-19%' group by Stock_id asc
)as s4 on s1.sid=s4.sid 
outer join
(
select stock.id as sid,stock.Name as sname, sum(orders.Quantity) as 'sum5' from orders inner join stock on `Stock_id`= stock.id where  orders.Created_at Like '2020-05-20%' group by Stock_id asc
)as s5 on s1.sid=s5.sid 

使用条件聚合:

select s.id as sid, s.Name as sname,
       sum(case when date(o.created_at) = '2020-05-16' then o.Quantity end) as sum1,
       sum(case when date(o.created_at) = '2020-05-17' then o.Quantity end) as sum2,
       sum(case when date(o.created_at) = '2020-05-18' then o.Quantity end) as sum3,
       sum(case when date(o.created_at) = '2020-05-19' then o.Quantity end) as sum4,
       sum(case when date(o.created_at) = '2020-05-20' then o.Quantity end) as sum5
from orders o inner join
     stock s
     on o.Stock_id = s.id 
group by s.id;

这要简单得多,不需要挑剔的 join 或子查询。此外,它修复了日期算法。