即使为0,也返回计数(*)

时间:2012-06-07 12:54:59

标签: sql sql-server tsql join group-by

我有以下查询:

select bb.Name, COUNT(*) as Num from BOutcome bo 
JOIN BOffers bb ON bo.ID = bb.BOutcomeID 
WHERE bo.EventID = 123 AND bo.OfferTypeID = 321 AND bb.NumA > bb.NumB 
GROUP BY bb.Name

表格如下:

Name | Num A | Num B
 A   |   10  |   3
 B   |   2   |   3
 C   |   10  |   3
 A   |   9   |   3
 B   |   2   |   3
 C   |   9   |   3

预期输出应为:

Name | Count
 A   |   2 
 B   |   0  
 C   |   2  

因为当名字是A和C时,Num A比Num B大,当Name是B时,在两个记录中Num A都低于Num B.

我目前的输出是:

Name | Count
 A   |   2 
 C   |   2   

因为B的输出是0,我在查询中没有得到它。

我的查询有什么问题?我应该怎么回来?

2 个答案:

答案 0 :(得分:5)

这是我的猜测。我认为这比人们一直在转动轮子的所有左/右连接圈都简单得多。由于查询的输出仅依赖于左表中的列,因此根本不需要显式连接:

SELECT 
  bb.Name, 
  [Count] = SUM(CASE WHEN bb.NumA > bb.NumB THEN 1 ELSE 0 END)
  -- just FYI, the above could also be written as:
  -- [Count] = COUNT(CASE WHEN bb.NumA > bb.NumB THEN 1 END)
FROM dbo.BOffers AS bb
WHERE EXISTS 
(
    SELECT 1 FROM dbo.BOutcome 
    WHERE ID = bb.BOutcomeID
    AND EventID = 123
    AND OfferTypeID = 321
)
GROUP BY bb.Name;

当然,我们并非确实确保Name和NumA / NumB都在左表中,因为OP会讨论两个表,但只显示示例数据中的一个表。我的猜测是基于他所说的“工作”但由于显式连接而缺少行的查询。

答案 1 :(得分:0)

另一个狂野的猜测。随意downvote:

SELECT ba.Name, COUNT(bb.BOutcomeID) as Num 
FROM 
        ( SELECT DISTINCT ba.Name
          FROM 
                  BOutcome AS b
              JOIN
                  BOffers AS ba
                      ON  ba.BOutcomeID  = b.ID
          WHERE b.EventID = 123 
            AND b.OfferTypeID = 321
        ) AS ba
    LEFT JOIN 
        BOffers AS bb 
            ON  AND bb.Name = ba.Name
            AND bb.NumA > bb.NumB
GROUP BY ba.Name ;