SQL - 多个计数作为附加列

时间:2012-08-02 11:18:58

标签: 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 

所以我将留下一个看起来像这样的结果集:

Owner      Total Lines    Total Sold    Total Lost    

Person1    124            112           12

我似乎无法正确查询。我试图使用子选择,但显然缺少某些东西,任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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