简体   繁体   English

如何确定同一行(Python,SQLite3)中三列的最大值

[英]How do I determine the highest value of three columns from the same row, Python, SQLite3

I am trying to display the results of a basic arithmetic test created in python, the test is repeated three times and collects three scores, this works fine, however whe I try to display these by the highest score of the three in descending order I am displayed an error message. 我正在尝试显示在python中创建的基本算术测试的结果,该测试重复了三遍并收集了三个分数,这很好用,但是我尝试按降序显示三个分数中的最高分数显示这些显示错误消息。 which is as follows. 如下。

Traceback (most recent call last):
  File "F:\Adair,Rowan CA2\Task 3\Code\DisplayTablesScore.py", line 4, in <module>
    cursor.execute("SELECT * FROM class1 ORDER BY (score1,score2,score3) DESC")
sqlite3.OperationalError: near ",": syntax error

However when it is organised by one of the columns eg only score 1 it works fine. 但是,如果按某一列进行组织(例如仅评分1),则效果很好。 The code that I cannot figure out how to fix is below. 我无法弄清楚如何修复的代码如下。

import sqlite3
connection = sqlite3.connect("class1.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM class1 ORDER BY (score1,score2,score3) DESC")
print("Class 1:")
result = cursor.fetchall() 
for r in result:
    print(r)

Any help with this would be immensly appreciated, I am also trying to determine the average aswell. 任何帮助,我们将不胜感激,我也在努力确定平均值。

First the syntax of ORDER BY its wrong, should be 首先,ORDER BY的语法错误,应为

SELECT * FROM class1 ORDER BY score1 DESC, score2 DESC, score3 DESC;

Based in the response of Max of multiple columns , if you need to order by the high score of the columns, you need to calculate them 根据多列Max的响应,如果您需要按列的高分排序,则需要计算它们

SELECT score1, score2, score3,
    CASE
    WHEN score1 >= score2 AND score1 >= score3 THEN score1
    WHEN score2 >= score1 AND score2 >= score3 THEN score2
    WHEN score3 >= score1 AND score3 >= score2 THEN score3
    ELSE score1
END AS high_score FROM class1 ORDER BY high_score DESC;

The SQL clause ORDER BY doesn't take parentheses when declaring its arguments. SQL子句ORDER BY在声明其参数时不带括号。 In other words, doing ORDER BY (...) is indeed invalid syntax. 换句话说,执行ORDER BY (...)确实是无效的语法。

To declare multiple columns to order against, just omit the parentheses: 要声明要排序的多列,只需省略括号:

cursor.execute("SELECT * FROM class1 ORDER BY score1 DESC, score2 DESC ,score3 DESC")

This example should cover the basics. 此示例应涵盖基础知识。 Note that each column may require its own descension/ascension keyword. 请注意,每列可能需要其自己的降序/升序关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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