简体   繁体   中英

psycopg2 Python concatenate percentage '%' in field postgresql

This is a pretty specific question, but I'm running an automated script through Python that runs a Postgresql query using psycopg2. One of the fields returns percentages, but instead of showing them as a whole number, I want to show add a percentage after each number. For instance, I have this line in my query:

CASE WHEN (delivered_orders != 0) then round((scanned_deliveries::numeric 
/ delivered_orders::numeric)*100) when delivered_orders = 0  then 0 end as 
scan_percent

So if there's 4 orders and 3 are scanned, it will return 75. I want it to return 75%. I have tried concatenating it with || '%' and || % after the "end", but Python treats the percentage as a placeholder and it says Tuples out of range because I don't have enough values. I have also tried playing along with using it as a placeholder and then putting '%' when I do cursor.execute(query, ('%')) but it says:

ValueError: unsupported format character

I have tried a few other things as well. I'm banging my head against the wall here and thought you smart people might know what I need to do. Thanks for your help!

Use %% for literal % . From the Psycopg docs :

When parameters are used, in order to include a literal % in the query you can use the %% string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM