左边加入空子查询时如何设置默认值

时间:2016-05-06 08:08:37

标签: mysql

我正在尝试计算与每个卖家相关的销售数量。我已经设法通过加入子查询来实现整体销售,如下所示:

SELECT seller.*, COALESCE(apc,0) AS total_sales
FROM seller
LEFT JOIN (
    SELECT seller_id, COUNT(seller_id) AS apc
    FROM purchase
    GROUP BY seller_id
) AS ap ON ap.seller_id = seller.id

但是,我还想计算过去三个月的销售数量,因此我将查询扩展到:

SELECT seller.*, COALESCE(apc,0) AS total_sales, COALESCE(rpc,0) AS recent_sales
FROM seller
LEFT JOIN (
    SELECT seller_id, COUNT(seller_id) AS apc
    FROM purchase
    GROUP BY seller_id
) AS ap ON ap.seller_id = seller.id
LEFT JOIN (
    SELECT seller_id, COUNT(seller_id) AS rpc
    FROM purchase
    GROUP BY seller_id
    WHERE purchase.time_created > [date three months ago]
) AS rp ON rp.seller_id = seller.id

当我运行此查询时,我收到错误Unknown column 'rpc',我认为这是因为当前数据集在过去三个月内没有销售,因此rp子查询将返回空白。

我已经使用COALESCE函数来处理字段中的空值,但是这第二个子查询似乎甚至没有创建包含任何空字段的表。

有没有办法为此设置一些默认值?

0 个答案:

没有答案