【问题标题】:how to find the sum of multiple numbers from a column in a sql database in python?如何从python中的sql数据库中的列中找到多个数字的总和?
【发布时间】:2017-01-31 19:15:38
【问题描述】:

我有一个包含 bookings 表的数据库。bookings 表中的一列是“收入”,另一列是“date_of_booking”,它以“DD/MM/YYYY”格式存储日期。我正在尝试编写一个功能,让用户输入一个月,然后计算该月的所有收入。到目前为止,我有这个:

    validMonth = False
    while not validMonth:
    lookForMonth = input('What month, please? (number from 1 through 12):')
    try:
        validMonth = 1<=int(lookForMonth)<=12
    except:
        pass

    sqlCmd = 'SELECT date FROM bookings WHERE SUBSTR(date,4,2)="%.2i"' %    int(lookForMonth)
    for row in conn.execute(sqlCmd):
    print (row)

使用此代码,我可以输出特定月份的预订日期。但是我想输出特定月份的总收入。我需要添加什么才能计算出特定月份的总收入并输出?任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python sql sum multiple-columns


    【解决方案1】:

    替换一条语句。

    SELECT sum(income) FROM bookings where SUBSTR(date,4,2)='04'
    

    如:

    import sqlite3
    conn = sqlite3.connect(':memory:')
    c = conn.cursor()
    c.execute('CREATE TABLE bookings (date text, income real)')
    c.execute('''INSERT INTO bookings VALUES ('01/04/2017', 19.22)''')
    c.execute('''INSERT INTO bookings VALUES ('15/04/2017', 19.22)''')
    c.execute('''INSERT INTO bookings VALUES ('22/04/2017', 19.22)''')
    
    validMonth = False
    while not validMonth:
        lookForMonth = input('What month, please? (number from 1 through 12):')
        try:
            validMonth = 1<=int(lookForMonth)<=12
        except:
            pass
    
    
    sql = '''SELECT sum(income) FROM bookings where SUBSTR(date,4,2)="%.2i"''' % int(lookForMonth)
    for row in c.execute(sql):
        print (row)
    

    结果输出:

    What month, please? (number from 1 through 12):4
    (57.66,)
    

    【讨论】:

    • 一个问题,我怎么能改变 'sql = '''SELECT sum(income) FROM bookings where SUBSTR(date,4,2)="04"''' ' line 这样它让用户输入一个月,应该搜索月份'04'?
    【解决方案2】:

    首先,您要在 sql 语句中同时选择两者。

    sqlCmd = 'SELECT date_of_booking,incomes FROM bookings WHERE SUBSTR(date,4,2)="%.2i"' %    int(lookForMonth)
    income_sum = 0
    for (row_date, row_income) in conn.execute(sqlCmd):
        income_sum += row_income
        print row_date
    
    print income_sum
    

    然后您可以像上面一样在循环中指定行的日期和收入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2019-02-01
      相关资源
      最近更新 更多