0

这个问题与我之前的帖子有关:MySQL - 查询中的复杂 SUM

该查询运行良好,可以根据需要汇总总数。我注意到它也忽略了任何具有 NULL 值的记录。

当前查询:

SELECT c.*,
        SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
        SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
        SUM(total) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

它还漂亮地返回了10条客户记录。当我检查数据库时,我可以看到11tbl_customers_bills条客户记录,而第 11 条在表中没有相关记录。

即使tbl_customers_bills表中不存在记录,我仍想返回所有 11 个。(但当然是零)

我不知道这种情况会变得多么复杂。这是我尝试过的:(无济于事)

SELECT c.*,

     (CASE WHEN (total IS NULL) THEN totalpaid = 0

       ELSE
        SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
        SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
        SUM(total) AS totalbalance
      END)

FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid
4

2 回答 2

2

我很可能完全属于但我相信你只是失踪了COALESCE

SELECT c.*,
       COALESCE(SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END), 0) totalpaid ,
       COALESCE(SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END), 0 totalowed ,
       COALESCE(SUM(total), 0) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

来自MySQL 参考

合并(值,...)

返回列表中的第一个非 NULL 值,如果没有非 NULL 值,则返回 NULL。

mysql> SELECT COALESCE(NULL,1); -> 1
mysql> 选择 COALESCE(NULL,NULL,NULL); -> 空

于 2013-01-17T07:30:28.437 回答
1

怎么做 ifnull

SELECT 
    c.*,
    SUM(CASE WHEN billtype = 1 THEN IFNULL(total,0) ELSE 0 END) totalpaid ,
    SUM(CASE WHEN billtype = 2 THEN IFNULL(total,0) ELSE 0 END) totalowed ,
    SUM(total) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid
于 2013-01-17T07:25:56.947 回答