使用SQL中的count函数发出问题

时间:2011-10-03 20:14:57

标签: sql-server-2008 stored-procedures count

我正在运行此查询,以计算使用保险的销售总数和没有保险的销售总数。但是,由于某种原因,所有用户都获得相同的计数。如何更改查询以显示每个用户总数。

我想要的基本上是弄清楚每个用户有多少预订和没有保险销售

bookingby是代理商

和T0是包含有关不包括保险的预订信息的表格

和t1是包含有关保险预订的信息的表

虽然两个表都提供相同的信息,但我如何通过两个表中的每个代理商预订总数

 SELECT   t0.BookedBy, count(t0.resnumber) as NonInsurance, COUNT(t1.resnumber) as Insurance  
    FROM (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
              FROM dbo.ResGeneral
              WHERE ResNumber NOT IN (SELECT ResNumber FROM dbo.ResItinerary_insurance) 
                  and  ResStatus = 'a'
              GROUP BY BookedBy, ResNumber, BookDate) t0 
        left JOIN (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
                       FROM dbo.ResGeneral
                       WHERE ResNumber IN (SELECT ResNumber FROM dbo.ResItinerary_insurance)
                           and  ResStatus = 'a') t1         
            ON t1.year = t0.year         
    group by t0.bookedby

2 个答案:

答案 0 :(得分:2)

认为这个查询是等价的:

SELECT g.BookedBy,
       SUM(CASE WHEN i.ResNumber IS NULL THEN 1 ELSE 0 END) AS NonInsurance,
       SUM(CASE WHEN i.ResNumber IS NOT NULL THEN 1 ELSE 0 END) AS Insurance
    FROM dbo.ResGeneral g
        LEFT JOIN dbo.ResItinerary_insurance i
            ON g.ResNumber = i.ResNumber
    WHERE g.ResStatus = 'a'
    GROUP BY g.BookedBy;

答案 1 :(得分:1)

您的加入条件看起来不正确:

 ON t1.year = t0.year 

这将在同一年交叉加入所有行。您可能希望使用更具体的条件,例如t1.BookedBy = t0.BookedBy