2

我有以下查询:

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  

因为当 name 为 A 和 C 时,Num A 比 Num B 大几倍,而当 Name 为 B 时,在两个记录中,Num A 都低于 Num B。

我目前的输出是:

Name | Count
 A   |   2 
 C   |   2   

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

我的查询有什么问题?我该如何取回它?

4

2 回答 2

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;

Of course, we're not really sure that both Name and NumA/NumB are in the left table, since the OP talks about two tables but only shows one table in the sample data. My guess is based on the query he says is "working" but missing rows because of the explicit join.

于 2012-06-07T14:01:04.693 回答
0

另一个疯狂的猜测。随意投反对票:

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 ;
于 2012-06-07T13:51:33.037 回答