I am trying to retrieve data from a sqlite data base. The goal is to get the sum of expenses per day. The code: (it is not correctly formatted)
db = SQL("sqlite:///financetracker.db")
test = db.execute("""
SELECT SUM(amount) AS total_amount, strftime('%Y', timestamp) AS year, strftime('%m', timestamp) AS month, STRFTIME('%d', timestamp) AS day
FROM transactions
WHERE exp = 1 AND user_id = 1 AND year = strftime('%Y', 'now') AND month = strftime('%m', 'now')
GROUP BY year, month, day
ORDER by timestamp DESC
""")
I am using the sql module from the cs50 library. exp is a column that contains booleans. This way I filter out the expenses.
As you can see, during the SELECT I add three additional columns: year, month and day and I calculate the sum per day. The dates are taken from another timestamp column in the same table. In this case test should be a list of dictionaries. The outcome looks like this:
total_amount | year | month | day |
---|---|---|---|
6.5 | 2021 | 01 | 29 |
20 | 2021 | 01 | 28 |
The SELECT works perfectly when I do it in phpliteadmin. Every column appears. But for some reasons the shown python script does not return the columns year, month and day. Only total_amount.
The following code:
day_1 = test[0]['day']
results in a key error:
KeyError: 'day'
fetchall()
– Marktest
between the execute andday_1 = test[0]['day']
. That sql will return dictionaries with all 4 keys whenever rows are selected. If no rows are selected thisday_1 = test[0]['day']
would give a different error (index out of range). – DinoCoderSaurus