如何在视图中连接多个子查询

时间:2013-10-17 10:34:31

标签: mysql sql

我有以下简化视图。您可以看到我在同一个表上有多个子查询。有没有办法将其作为一个单一的子查询?类似的东西:

(select count(*), sum(..), max(..) from XY1 .....) as (Count1, Sum1, Max1),
(select count(*), sum(..), max(..) from XY2 .....) as (Count2, Sum2, Max2),

这是代码:

drop view if exists view_OffersStat;
create view view_OffersStat as

select
o.Id as Offer_Id,
o.Title,
o.Start,
o.Expires,

(select count(*) from Sale as s where s.Merchant_Id=o.Merchant_Id) as Total_Sales,
(select sum(s.Net) from Sale as s where s.Merchant_Id=o.Merchant_Id) as Total_Net,
(select sum(s.Gross)) from Sale as s where s.Merchant_Id=o.Merchant_Id) as Total_Gross,
(select max(s.Gross) from Sale as s where s.Merchant_Id=l.Merchant_Id) as Max_Gross,

from Offer as o;

1 个答案:

答案 0 :(得分:1)

drop view if exists view_OffersStat;
create view view_OffersStat as

select
o.Id as Offer_Id,
o.Title,
o.Start,
o.Expires,
count(*) as Total_Sales,
sum(s.Net) as Total_Net,
sum(s.Gross) as Total_Gross,
max(s.Gross) as Max_Gross,

from Offer as o
inner join Sale as s
on s.Merchant_Id=o.Merchant_Id
group by s.Merchant_Id;