我正在按城镇创建报告订单。

SELECT S.city, count(*) as NumOfOrders
    FROM Shop as S
    LEFT JOIN orders O ON O.ShopID = S.ShopID
WHERE O.status = 4
Group by S.city


结果显示如下:

Town 1  |   53
Town 2  |   45
Town 3  |   64


它工作正常,但我想显示所有城镇,甚至没有订单?

预期结果:

Town 1  |   53
Town 2  |   45
Town 3  |   64
Town 4  |   0
Town 5  |   0


我尝试将LEFT JOIN替换为RIGHT JOIN,这甚至不起作用。结果相同。

最佳答案

尽管您使用的是LEFT JOIN,但是您使用的是Where子句中的o.statu列,因此具有空值(左联接的余弦)的行将被删除。

尝试这个:

SELECT S.city,
        SUM
        (
        CASE
            WHEN ISNULL(O.status) THEN 0
            ELSE 1
        END
        ) as NumOfOrders
    FROM Shop as S  LEFT JOIN orders O
      ON O.ShopID = S.ShopID
 WHERE IFNULL(O.status, 4) = 4
    GROUP BY S.city

10-08 04:41