Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select min and max from table by column score?

Tags:

sqlalchemy

How to select min and max from table by column score ? Is this possible with session query ?

class Player(Base):
    username = Column(String)
    score = Column(Integer)
    # more not impoortant columns
like image 647
PaolaJ. Avatar asked Jan 08 '13 15:01

PaolaJ.


People also ask

How do you SELECT the maximum and minimum values of a column in SQL?

To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value.

How do you find the maximum and minimum values of a table?

SQL MIN() & MAX() functions are used to find the lowest value and largest value of a column respectively. MIN(column_name): It returns the lowest value of the column. MAX(column_name): It returns the largest value of the column.

How do you SELECT a maximum value in a column in SQL?

Discussion: To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

Can we use max and min together in SQL?

You can use both the MIN and MAX functions in one SELECT . If you use only these functions without any columns, you don't need a GROUP BY clause. In the SELECT , we have the MIN() function with the price column argument followed by MAX() with the same argument and their respective aliases.


2 Answers

For the case when you need to find minimum and maximum values for the score field. You can do this with a one query using min and max functions:

from sqlalchemy.sql import func
qry = session.query(func.max(Player.score).label("max_score"), 
                func.min(Player.score).label("min_score"),
                )
res = qry.one()
max = res.max_score
min = res.min_score
like image 114
vvladymyrov Avatar answered Sep 22 '22 08:09

vvladymyrov


from sqlalchemy import func
max = session.query(func.max(Table.column)).scalar()
min = session.query(func.min(Table.column)).scalar()
like image 44
Vlad Bezden Avatar answered Sep 24 '22 08:09

Vlad Bezden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!