2017-01-31 2 views
1

私は予約テーブルを持っているデータベースを持っています。予約テーブルの列の1つは「収入」で、もう1つは「日付/月/年」形式の日付を格納する「date_of_booking」です。ユーザーが月を入力できるようにする機能を作成しようとしており、その月のすべての収入を計算します。これまで私はこれを持っています:pythonのSQLデータベースの列から複数の数値の合計を見つける方法は?

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) 

このコードでは、特定の月の予約の日付を出力することができます。しかし、私は特定の月の総所得を出力したいと思います。特定の月の総所得を計算して出力するには、何を追加する必要がありますか?どんな助けでも喜んで感謝します、ありがとう。

答えて

0

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,) 
+0

これは驚くべきです!どうもありがとうございます!!!! :D – brenda

+0

しかし、私は 'sql =' '' SUBSTR(date、4,2)= "04" '' ''行のSELECT集計(FROM)予約をどのように変更することができますか?今月の「04」を探していた月ですか? – brenda

+0

自分のコードに合わせて回答が変更されました –

0

まず、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 

次に、上記のようにループの日付と所得を指定できます。

関連する問題