如果按月分组并且如果某个月没有值则返回零?

时间:2016-07-25 06:51:50

标签: mysql sql node.js

这是我的mysql收入表。

+----+------------------+---------------------------+------------+---------+
| id | title            | description               | date       | amount  |
+----+------------------+---------------------------+------------+---------+
|  1 | Vehicle sales up | From new sale up          | 2016-09-09 | 9999.99 |
|  2 | Jem 2 Sales      | From rathnapura store     | 2016-05-15 | 9545.25 |
|  3 | Jem 2 Sales 2    | From rathnapura store     | 2016-05-15 | 9545.25 |
|  4 | Jem 2 Sales 2    | From rathnapura store 234 | 2016-05-15 | 9545.25 |
+----+------------------+---------------------------+------------+---------+

字段'日期'是标准的sql日期。我执行此查询是为了按月收入总和,如果没有某个月的收入,则返回零。如果没有某个月的收入,我想要零,因为我想在图表中显示这些数据。

这是查询。

SELECT MONTHNAME(`date`) AS mName, MONTH(`date`) AS mOrder, ifnull(sum(amount),0) AS total_num FROM income GROUP BY mOrder ORDER BY mOrder DESC

但我只得到如下输出。如果其他月份没有值,则不为零。这是输出。

+-----------+--------+-----------+
| mName     | mOrder | total_num |
+-----------+--------+-----------+
| September |      9 |   9999.99 |
| May       |      5 |  28635.75 |
+-----------+--------+-----------+

我希望上表中的其他月份和total_num为零。我怎样才能做到这一点?那里也有同样的问题。但没有工作的答案。 Group by month and return 0 if data not found

请帮我解决这个问题。我用于此应用程序的语言是Node.JS:)

3 个答案:

答案 0 :(得分:2)

列出所有月份,然后left join到您的桌子:

SELECT MONTHNAME(m.month) AS mName, 
    MONTH(m.month) AS mOrder, 
    ifnull(sum(amount),0) AS total_num 
from months m
left join income i
on m.month = i.date

GROUP BY mOrder 
ORDER BY mOrder DESC

如果您不想创建months表,则可以:

(select STR_TO_DATE('01/01/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/02/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/03/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/04/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/05/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/06/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/07/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/08/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/09/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/10/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/11/2016', '%d/%m/%Y') as month union 
 select STR_TO_DATE('01/12/2016', '%d/%m/%Y') as month)

答案 1 :(得分:1)

也许这不是最好的方法,但它会解决你的问题。快速的说法:

SELECT 'January' AS mName, 1 AS mOrder, COALESCE(SUM(amount),0) AS total_num 
FROM income i
WHERE month(i.date) = 1

UNION

SELECT 'February' AS mName, 2 AS mOrder, COALESCE(SUM(amount),0) AS total_num 
FROM income i
WHERE month(i.date) = 2

UNION

...and go on

答案 2 :(得分:0)

您应该创建一个CALENDAR表,具有您需要的精度,在这种情况下为几个月。

+-----------+
| Month     |
+-----------+
| January   |   
| February  |      
.......

加入吧