在MySQL查询中显示零计数

时间:2012-09-02 08:07:01

标签: mysql select count

我的数据库中有一个名为subscriber的表,其中包含两个用于订户ID的行,另一个用于每个订户获得的点数。 我的选择查询:

SELECT 1000 * ( LOYALTY_POINTS DIV 1000 ) AS  'from', 1000 * ( LOYALTY_POINTS DIV 1000 ) +1000 AS  'to', COUNT( * ) AS NUMBER FROM SUBSCRIBER GROUP BY LOYALTY_POINTS DIV 1000 

应该为每个点数返回订阅者数量,但不幸的是它只返回不同于零的订阅者数量。 我的结果是:

从到NUMBER 0 1000 8
1000 2000 2
3000 4000 1

我希望查询返回零国家的记录。 结果应该是:

从到NUMBER 0 1000 8
1000 2000 2
2000 3000 0
3000 4000 1

怎么做?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您需要生成一些数字来表明您的范围

 SELECT 0 as RangeStart UNION Select 1000 UNION Select 2000 UNION Select 3000

并将LEFT JOIN加入到您的结果中。

SELECT 
    RangeStart, RangeStart + 999 as RangeEnd, RangeCount
FROM
    (SELECT 0 as RangeStart UNION Select 1000 UNION Select 2000 UNION Select 3000) range
         LEFT JOIN
    (Select LoyaltyPoints DIV 1000 as loyaltypoints, count(*) as RangeCount group by LoyaltyPoints DIV 1000 ) counts
    ON range.rangestart = counts.loyaltypoints