如果没有按分组依据的mysql SUM查询中的记录,则使零而不是null

时间:2019-05-20 13:40:22

标签: php mysql arrays

我编写了一个查询,以按日期获取每个产品组的总金额之类的结果。
 获取输出时,某些产品的日期没有相应的金额。该日期未在输出中列出,因此我需要显示每个日期,如果有金额,则需要显示金额,否则为0。

我尝试使用IFNULL和COALESCE,但得到相同的输出。

My OUTPUT 

 date         amount
 2019-05-16   499
 2019-05-17   1998
 2019-05-18   999
 2019-05-19   999

Needed output should look like this

 date         amount
 2019-05-16   499
 2019-05-17   1998
 2019-05-18   999
 2019-05-19   999
 2019-05-20   0


查询从mysql获取数据

$query = "select date, SUM(amount) as amount from product_details where date between '2019-05-16 00:00:00' and '2019-05-20 23:59:59' and prodid = 1 group by date";

有什么办法可以显示没有金额的日期?

1 个答案:

答案 0 :(得分:0)

尝试一下。首先,我们生成一个记录集,其中包含curdate()和一月一月之间的所有日期。将curdate()更改为结束日期,并将1月1日更改为开始日期。 然后我们将其与您的表进行外部连接,并使用它按日期分组。

  With cal as  (SELECT a.Days 
    FROM (
        SELECT curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Days
        FROM       (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
        CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
    ) a
    WHERE a.Days >= '2019-01-01' and a.Days<=curdate()) 
    SELECT cal.Days as date, sum(p.amount)  as amount FROM cal LEFT JOIN product_details p  on cal.Days=p.date and p.prodid=1 group by cal.Days