Im trying to make a discord command that gets a column of a database greatest to least and gets the top 10 results, its working but its not printing in order greatest to least.
cursor.execute(f"SELECT bal, user_id FROM moneyTable WHERE guild_id = {ctx.guild.id} ORDER BY bal DESC LIMIT 10")
result = cursor.fetchall()
print(result)
My result is
[('635', '673990922945560599'), ('400', '317652126471815168'), ('200', '323669516489850882'), ('15000', '539305505445642250'), ('1260', '448573840893804614'), ('1000', '531664615755612161'), ('100', '419300570235666432'), ('100', '412106756349624331'), ('100', '408674114958524417'), ('100', '358517557772156929')]
It seems like the data type of bal is TEXT so it is ordered alphabetically.
You must convert bal to an integer either by adding 0 or explicitly:
SELECT bal, user_id
FROM moneyTable
WHERE guild_id = {ctx.guild.id}
ORDER BY bal + 0 DESC LIMIT 10
or:
SELECT bal, user_id
FROM moneyTable
WHERE guild_id = {ctx.guild.id}
ORDER BY CAST(bal AS INTEGER) DESC LIMIT 10
Related
I believe that I need to to expand the sql statement as the current one I have:
SELECT OrderID FROM Orders WHERE UserID = (?)
is likely to cause problems in the future when there are users with multiple orders. Is there a way that I can select and use the autoincrementing orderID in my orders table in combination?
For reference, my DB looks like this:
And the python I currently have is like this however I feel that it may have to be rewritten entirely.
results[0][0] is the ID of the current user from the Users table
elif userinput == "5":
basket = []
print(pd.read_sql_query('SELECT * FROM Products', conn))
shopping = True
while shopping:
itemToAdd = input("Please enter the ID of the item to add to the basket: ")
basket.append(itemToAdd)
print(basket)
continueShop = input("Continue shopping?(y/n): ")
if continueShop == "n":
conn.execute("INSERT INTO Orders (UserID) VALUES (?)", (results[0][0],))
conn.commit()
counter = 0
for items in basket:
createOrderItems = "INSERT INTO OrderItems (OrderID, ProductID) VALUES (?,?)"
currentOrder = ("SELECT OrderID FROM Orders WHERE UserID = (?) ", (results[0][0]))
conn.execute(createOrderItems, (currentOrder[0], basket[counter]))
counter = +1
conn.commit()
Because the database is built using the DB Browser application, I really have no clue how to access the parts of it that I need to ensure I am selecting the right record. Any help is appreciated, thanks.
Also, since the primary key of each table is autoincrementing I need a way to select only the record that was created just now using
conn.execute("INSERT INTO Orders (UserID) VALUES (?)",
However, I cannot think of a way to do so even though the record is unique in the orders table, as there is no way of knowing which order is the one that needs to be looked at as far as I can tell
You can use the lastrowid attribute of the cursor object to find the id of the inserted order. Then use a compound WHERE in the select statement (ie WHERE userid = something and orderid = something_else).
I am trying to figure out a SQL query or a Python Pandas code for the following solution.
There are n number of USER_ID with various transactions.
Every USER_ID has more than one transaction.
Example USER_ID
000e88bb-d302-4fdc-b757-2b1a2c33e7d6
001926be-3245-43fa-86dd-b40ee160b6f9
Every Transaction has a TYPE
TOPUP
Bank_Transaction
P2P
and a couple more
I want to write a query in which
(TOPUP) - (total of every other type of transaction) and returns all the USER_ID where TOPUP < Total of all the transactions.
Finding all the users who have less topup and more spending.
I hope I am making myself clear?
I believe that the following may produce the result that you want :-
WITH counter AS (
SELECT user_id
FROM transactions AS a
WHERE
coalesce((SELECT sum(amount) FROM transactions WHERE transaction_type = 'TOPUP' AND user_id = a.user_id),0.0) -
coalesce((SELECT sum(amount) FROM transactions WHERE transaction_type <> 'TOPUP' AND user_id = a.user_id),0.0)
< 0
GROUP BY user_id
)
SELECT count() FROM counter;
this assumes that the table name is transactions.
If you consider the following data :-
INSERT INTO transactions VALUES
('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','TOPUP',25.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','P2P',125.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','TOPUP',25.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','TOPUP',25.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','TOPUP',25.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','TOPUP',25.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('000e88bb-d302-4fdc-b757-2b1a2c33e7d6','BANK-TRANSACTION',75.00)
,('001926be-3245-43fa-86dd-b40ee160b6f9','TOPUP',10.00)
,('001926be-3245-43fa-86dd-b40ee160b6f9','TOPUP',10.00)
,('001926be-3245-43fa-86dd-b40ee160b6f9','TOPUP',10.00)
,('001926be-3245-43fa-86dd-b40ee160b6f9','TOPUP',10.00)
,('001926be-3245-43fa-86dd-b40ee160b6f9','TOPUP',10.00)
,('XX1926be-3245-43fa-86dd-b40ee160b6f9','P2P',50.00)
,('XX1926be-3245-43fa-86dd-b40ee160b6f9','P2P',50.00)
,('XX1926be-3245-43fa-86dd-b40ee160b6f9','P2P',50.00)
,('XX1926be-3245-43fa-86dd-b40ee160b6f9','P2P',50.00)
,('XX1926be-3245-43fa-86dd-b40ee160b6f9','P2P',50.00)
;
Then the result of the above is :-
i.e. the first and third users have a negative account balance, whilst the 2nd has a positive balance (and is therefore excluded from the count).
Think of the topup amounts to be positive and other spendings negative, then we are simply looking for users with a negative balance.
select user_id
from transaction
group by user_id
having sum(case when transaction_type = 'TOPUP' then amount else -amount end) < 0
I have this code in python querying an existing database:
count = db.execute("SELECT COUNT (player_id) FROM players WHERE user_id
= :id", id = session["user_id"])
for player in range(count):
db.execute("INSERT INTO live_players (player_id) VALUES (:filler)",
filler = 0)
However, it doesn't run because 'count' isn't an int. I want SELECT COUNT to return 2, but instead it returns '[{'COUNT (player_id)': 2}]'. How could I remedy this?
You're getting back a result dictionary. Simply access it. To make this access easier, give it an alias:
SELECT COUNT(player_id) AS player_count ...
Then:
for player in range(count["player_count"]):
...
Within my sqlite query, I'm attempting to not only get the count but also sum the count. This is what I have so far:
sql = c.execute("SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org ORDER BY NUM DESC")
sql_list = list(sql)
list_count = len(sql_list)
print("2014 Data:")
for i in sql_list:
print(i)
sql_sum = c.execute("SELECT SUM(NUM) FROM (SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='')")
sum_list = list(sql_sum)
print("Sum =", sum_list)
print()
I get the correct output for the first sql query, but I don't get the correct output for the second.
Any help would be much appreciated!
Thanks in advance!
If you're looking to get the sum of the table from your first sql statement, then it looks like you just missed adding the group by (GROUP BY Org) you had in the first query. without having the database and the expected results, below is what I expect will work for you.
sql = c.execute("SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org ORDER BY NUM DESC")
sql_list = list(sql)
list_count = len(sql_list)
print("2014 Data:")
for i in sql_list:
print(i)
sql_sum = c.execute("SELECT SUM(NUM) FROM (SELECT DISTINCT Org, COUNT(*) AS NUM FROM 2014Data WHERE Action='UPDATED' AND NewValue='' GROUP BY Org )")
sum_list = list(sql_sum)
print("Sum =", sum_list)
I have a database that has a bookings table in. One of the columns in the bookings table is 'incomes', and another one is 'date_of_booking,' which stores dates in 'DD/MM/YYYY' format. I am trying to write a feature that lets a user input a month, and from that will calculate all the incomes from that month. So far I have this:
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)
With this code, I am able to output the date of bookings for a particular month. However I want to output the total incomes for a particular month. What do I need to add so that this works out the total incomes for a particular month and outputs it? Any help would be gladly appreciated, thanks.
Replace one statement.
SELECT sum(income) FROM bookings where SUBSTR(date,4,2)='04'
As in:
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)
Resulting output:
What month, please? (number from 1 through 12):4
(57.66,)
First of all, you want to select both in your sql statement.
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
Then you can specify both date and income of the row in your loop like above.