如何创建计算每月人口增长的SQL查询

时间:2015-11-07 20:02:02

标签: mysql

我想创建一个SQL查询,计算在A月出生的婴儿数,然后它应该计算在B月出生的婴儿,但第二个记录应该有A个月加B的总和。例如;

    Month  |  Number
   --------|---------
     Jan   |    5
     Feb   |    7    <- Here were 2 babies born but it have the 5 of the previous month added
     Mar   |    13   <- Here were 6 babies born but it have the 7 of the two previous months added

也许有人可以帮我解决这个问题,是否可以做这样的事情?

我有一个带有babyID,BirthDate等的直接表。

非常感谢

1 个答案:

答案 0 :(得分:2)

考虑使用计算运行计数的子查询。内部和外部查询都是查询聚合组:

使用以下示例数据:

babyID  Birthdate
1       2015-01-01
2       2015-01-15
3       2015-01-20
4       2015-02-01
5       2015-02-03
6       2015-02-21
7       2015-03-11
8       2015-03-21
9       2015-03-27
10      2015-03-30
11      2015-03-31

SQL查询

SELECT MonthName(BirthDate) As BirthMonth, Count(*) As BabyCount,

      (SELECT Count(*) FROM BabyTable t2
      WHERE Month(t2.BirthDate) <= Month(BabyTable.BirthDate)) As RunningCount

FROM BabyTable
GROUP BY Month(BirthDate)

<强>输出

BirthMonth  BabyCount   RunningCount
January            3              3
February           3              6
March              5              11