0

我有一个查询:

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 

所以我会得到一个看起来像这样的结果集:

Owner      Total Lines    Total Sold    Total Lost    

Person1    124            112           12

我似乎无法正确查询。我正在尝试使用子选择,但显然缺少一些东西,我们将不胜感激。

4

3 回答 3

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

如果你想水平排列它,你需要一个 PIVOT。这取决于您的各种 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
于 2012-08-02T11:24:38.690 回答
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
于 2012-08-02T11:26:52.870 回答
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
于 2012-08-02T11:26:56.970 回答