0

我有查询表,字段如下

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
4

1 回答 1

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

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

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

于 2013-03-21T10:53:17.137 回答