MySQL查询以查找每个月年的计数(id)

时间:2019-06-25 15:42:04

标签: python mysql sql

我正在重构我的代码。而且我正试图在单个查询中获得python脚本的结果。

我试图这样做:

  select year(created), month(created), count(*) as total_id
  from repository_clinicaltrial
  group by id, year(created), month(created)
  order by id, year(created), month(created);

获取每个MONTH年的ID计数。

我正在使用python进行这种操作:

dic_months = {1: "jan",
         2: "fev",
         3: "mar",
         4: "abr",
         5: "mai",
         6: "jun",
         7: "jul",
         8: "ago",
         9: "set",
         10: "out",
         11: "nov",
         12: "dez"
        }

def retorna_dic_report(yearI):

    yearN = yearI + 1


    query_report = 'select created from repository_clinicaltrial where created >= "%s-01-01" and created < "%s-01-01";' % (yearI,
                                                                                                                          yearN)


    db = MySQLdb.connect(host= host,
                  user= user,
                  passwd= pass,
                  db= db)
    cur = db.cursor()


    cur.execute(query_report)

    dic_result = {}
    for row in cur.fetchall():
            try:
               dic_result[dic_months[row[0].month]] = dic_result[dic_months[row[0].month]] + 1
            except:
               if row[0].month == 12:
               dic_result[dic_months[row[0].month]] = 1

    return dic_result

我想使用一个查询来返回几年内每个月的id计数。

有可能吗?

1 个答案:

答案 0 :(得分:1)

您每年和每月要排一行,因此应该是group by中的行。您还拥有id,这似乎不正确。所以:

select year(created), month(created), count(*) as total_id
from repository_clinicaltrial
group by year(created), month(created)
order by year(created), month(created);

注意:如果您缺少特定月份的日期,则该日期将不在您的结果集中。我不确定这是否与您的问题有关。