sql查询来计算表中的各个字段

时间:2013-03-21 10:34:45

标签: sql sql-server sql-server-2008

我正在查询表,字段在下面

sno     confname         region       enquiry   status update    closed      approval
 1     Conf 2020     Madhya Pradesh     test           test      closed      reconsider
 2     Conf 2013     Maharashtra       test 123        abcde                reconsider
 3     Conf 2013     Maharashtra        test12         test      closed      approved
 4     Conf 2013     Maharashtra        test124       test1      closed      approved 
 5     Conf 3        Karnataka          test124       test1                  
 6     Conf 3        Karnataka          test876       test45       
 7     Conf 3        Karnataka          test365       test45      closed     approved

我需要输出

Region          Conf Name    Total No of Enq   No of Enq Closed    No of Enq Approved 
Maharashtra     Conf 2013                3                2                        2
Karnataka       Conf 3                   3                1                        1
Madhya Pradesh  Conf 2020                1                1  

我的SQL查询是

SELECT confname,
       region,
       clsed ,
       apprstatus ,
       Count(region) AS totenq,
       Count(clsed) AS totenqclsd ,
       COUNT(apprstatus) AS totenqapproved
FROM [enquiries_dtls]
GROUP BY region,
         confname,
         clsed,
         apprstatus

1 个答案:

答案 0 :(得分:0)

您可以使用带有CASE表达式的聚合函数来获得结果:

select region,
  confname,
  count(*) TotalEnquiry,
  sum(case when closed is not null then 1 else 0 end) TotalClosed,
  sum(case when approval = 'approved' then 1 else 0 end) TotalApproved
from enquiries_dtls
group by region, confname

请参阅SQL Fiddle with Demo

编辑,如果需要根据这些列计算另一个值,请使用子查询:

select region,
  confname,
  TotalEnquiry,
  TotalClosed, 
  TotalApproved,
  TotalEnquiry - TotalApproved 
from
(
  select region,
    confname,
    count(*) TotalEnquiry,
    sum(case when closed is not null then 1 else 0 end) TotalClosed,
    sum(case when approval = 'approved' then 1 else 0 end) TotalApproved
  from enquiries_dtls
  group by region, confname
) src

请参阅SQL Fiddle with Demo