2012-08-02 42 views
0

我有一個查詢:SQL - 多計爲附加列

select e.Owner as 'Owner', COUNT(l.EnquiryID) as 'Total Sales Lines' 
from DayBookQuoteLines l, DayBookEnquiries e 
where l.EnquiryID = e.EnquiryID 
and MONTH(e.enquirydate) = 8 and YEAR(e.enquirydate) = 2012 
group by e.Owner 

這將返回包含一個名字和一個總列所有者列,但我希望有在那裏我將附加的過濾器兩列並重新計算,添加在:

l.LostStatusId =2 

l.LostStatusId =3 

,所以我會留下一個結果集,看起來升ike這樣的事情:

Owner  Total Lines Total Sold Total Lost  

Person1 124   112   12 

我似乎無法得到正確的查詢。我試圖使用子選擇,但我顯然缺少的東西,任何援助將不勝感激。

回答

1

當條件滿足時,您可以通過添加一個記錄來有條件地對記錄進行計數。

select e.Owner as 'Owner', 
     COUNT(l.EnquiryID) as 'Total Sales Lines', 
     sum(case when l.LostStatusId = 2 then 1 end) TotalSold, 
     sum(case when l.LostStatusId = 3 then 1 end) TotalLost 
    from DayBookQuoteLines l 
inner join DayBookEnquiries e 
    on l.EnquiryID = e.EnquiryID 
where MONTH(e.enquirydate) = 8 
    and YEAR(e.enquirydate) = 2012 
group by e.Owner 
+0

這正是我一直在後,謝謝。 – 2012-08-02 11:30:32

+0

@DeanMcGarrigle不客氣:-) – 2012-08-02 11:31:08

1

這會給你不同的總計

select e.owner, LostStatusID , COUNT(l.EnquiryID) 
from DayBookQuoteLines l 
    inner join DayBookEnquiries e 
    on l.EnquiryID = e.EnquiryID  
group by owner, LostStatusID with rollup 

如果你想水平佈置,你需要一個支點。這取決於你的各種SQL。

select owner, [2]+[3] as total, [2],[3] 
from 
(
    select e.owner, LostStatusID , l.EnquiryID 
    from DayBookQuoteLines l 
     inner join DayBookEnquiries e 
     on l.EnquiryID = e.EnquiryID  

) v 
    pivot 
(count(enquiryid) for LostStatusID in ([2],[3])) p 
1

很難沒有看到的模式來寫,但你有沒有試過這樣:

select 
    e.Owner as 'Owner', 
    COUNT(l.EnquiryID) as 'Total Sales Lines' 
    count(select count(a.salesMade) from DayBookQuoteLines where month=MONTH(e.enquirydate)) as totalSold, 
    count(select count(a.lostSales) from DayBookQuoteLines where month=MONTH(e.enquirydate)) as totalLost 
from 
    DayBookQuoteLines l, 
    DayBookEnquiries e 
where 
    l.EnquiryID = e.EnquiryID 
    and MONTH(e.enquirydate) = 8 
    and YEAR(e.enquirydate) = 2012 
group by e.Owner