显示其他每月字段,即使它们没有关于它们的数据

时间:2016-03-16 11:19:32

标签: mysql

我需要看到每个月的收入。所以我运行了这个查询:

Public Function GetFrequencyGrid() As String

        'Get/Set Variables
        Dim size As Integer = CInt((Globals.UsersNumbers.Length / 3))
        Dim start As Integer = 0
        Dim FreqArray(69) As Integer
        Dim num As Integer = 0


        'Count up digit Frequencies
        For x As Integer = 0 To size - 1
            num = CInt(Globals.UsersNumbers.Substring(start, 3))
            FreqArray(num) += 1
            start += 3
        Next 'Result: (0, 0) (1, 116) (2, 128) (3, 110) (4, 110), etc.
        Return Nothing

        End Function
End Class 

结果如下:

enter image description here

我真正想要的是,即使它们在第1,4,5,6到12个月没有数据,我需要将它们显示在这样的结果中:

SELECT 
    sum(project_cost), month(date_now)
FROM
    dentist.patient_info
WHERE
    year(date_now) = '2016'
GROUP BY month(date_now);

因为我要将它们作为JSON数组发送到AJAX中,并将它们显示在 chartJS的条形图中。

他们是这样做的吗?

3 个答案:

答案 0 :(得分:2)

使用left join和`coalesce():

SELECT mon.mon, COALESCE(sum(project_cost), 0)
FROM (SELECT 1 as mon 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 
      UNION ALL SELECT 10 
      UNION ALL SELECT 11 
      UNION ALL SELECT 12
     ) mon LEFT JOIN
     dentist.patient_info pi
     ON month(pi.date_now) = mon.mon
WHERE year(pi.date_now) = '2016'
GROUP BY mon.mon;

答案 1 :(得分:2)

这应该有效:

SELECT 
    sum(cost) as cost,
    month
FROM 
(
    SELECT 
        sum(project_cost) as cost, 
        month(date_now) as month 
    FROM 
        dentist.patient_info 
    WHERE year(date_now)='2016' 
    GROUP BY month(date_now)

    UNION 

    SELECT 
        sum(payment), 
        month(date_now) 
    FROM 
        YOUR_TABLE_HERE
    WHERE year(date_now)='2016' 
    GROUP BY month(date_now)

    UNION SELECT 0,1
    UNION SELECT 0,2
    UNION SELECT 0,3
    UNION SELECT 0,4
    UNION SELECT 0,5
    UNION SELECT 0,6
    UNION SELECT 0,7
    UNION SELECT 0,8
    UNION SELECT 0,9
    UNION SELECT 0,10
    UNION SELECT 0,11
    UNION SELECT 0,12
) tmp
GROUP BY month

工会只是将缺少的月份添加为0作为成本,因此总和为所有月份。

更新了包含其他sum的答案。这假设您的新表格也有date_now列,类似于dentist.patient_info

中的列

答案 2 :(得分:1)

SELECT SUM(project_cost),MONTH(date_now)FROM dentist.patient_info GROUP BY MONTH(date_now);

project_cost  |  date_now
100           |  2016-03-09
200           |  2016-02-01 
300           |  2016-02-16 
              |  2016-01-01
500           |  2016-02-02
              |  2016-04-01
288           |  2016-04-16
              |  2016-05-01
288           |  2016-05-16

我试过,它运行得很完美。

它显示这样的输出

0             |  1
1000          |  2 
100           |  3
288           |  4
288           |  5