2013-10-17 63 views
0

我有以下簡化視圖。你可以看到我在同一個表上有多個子查詢。有沒有辦法將它作爲一個單一的子查詢?是這樣的:如何在視圖中加入多個子查詢

(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
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; 
+0

感謝您的幫助,但它不工作。例如Sale表有350行,但Total_Sales給出的值爲3800 – webduvet

+0

怎麼回事?爲什麼Total_Sales的價值是3800? – david

+0

我的錯,我錯誤地閱讀它,如果我改變組由o.Id(報價,不出售),這一切工作感謝指出我正確的方向 – webduvet