如何使用 Python 中的 SQLAlchemy 對 SQL 列進行 GroupBy 和 Sum 操作?
當我們踏入 Python 及其強大的庫 SQLAlchemy 的領域時,就會發現一個充滿多功能操作的源泉。其中一項功能是對 SQL 列進行 GroupBy 和 Sum 操作,這在資料庫操作中至關重要。SQLAlchemy 是一款 SQL 工具包,也是 Python 的物件關係對映 (ORM) 系統,它提供了豐富的功能,可以以一種無縫且符合 Python 風格的方式促進 SQL 操作。讓我們深入瞭解如何利用 SQLAlchemy 對 SQL 列進行 GroupBy 和 Sum 操作。
語法
在本文中,我們將探討如何使用 SQLAlchemy(一個流行的 Python SQL 工具包)來執行 SQL 列的分組和求和。我們將演示兩種方法——ORM 會話方法和顯式會話方法。這兩種方法都會影響 SQLAlchemy 對資料庫任務的作用力,並提供簡潔直觀的語法。
Stmt=session.query(Sales.product,func.sum(Sales.quantity).label('total_quantity')).group_by(Sales.product)
演算法
分步說明:
匯入必要的模組。
與資料庫建立會話。
查詢資料庫,指定要進行分組和求和的列。
使用 group_by() 函式對資料進行分組。
使用 func.sum() 計算總和。
執行命令並獲取結果。
處理任何異常,並關閉會話。
方法 1:使用顯式會話
第一種方法是使用顯式會話,這非常適合基於應用程式的程式碼。
示例
from sqlalchemy import create_engine, Column, Integer, String, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# Create a new engine instance
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
# Define a new table with a name, metadata, and several columns
class Sales(Base):
__tablename__ = 'sales'
id = Column(Integer, primary_key=True)
product = Column(String)
quantity = Column(Integer)
# Create the table
Base.metadata.create_all(engine)
# Prepare data
data = [
Sales(product='Apples', quantity=5),
Sales(product='Oranges', quantity=7),
Sales(product='Apples', quantity=3),
Sales(product='Bananas', quantity=8),
Sales(product='Apples', quantity=6),
Sales(product='Oranges', quantity=9),
]
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
try:
# Add data to the session
session.add_all(data)
# Commit the changes
session.commit()
# Create a select statement
stmt = session.query(Sales.product, func.sum(Sales.quantity).label('total_quantity')).group_by(Sales.product)
# Execute the statement
results = stmt.all()
for result in results:
print(result)
finally:
# Close the session
session.close()
解釋
在這種方法中,我們遵循與前面方法類似的初始設定,建立引擎並定義表結構。我們使用 sessionmaker 手動建立會話工廠,並使用 Session() 開啟會話。在 try-finally 塊中,我們將資料新增到會話中,提交更改,並建立用於分組和求和的 select 語句。我們執行語句,處理結果,最後關閉會話。
這兩種方法提供了實現相同結果的不同方式。根據您的專案需求和編碼偏好,您可以選擇最適合您需求的方法。
方法 2:使用 ORM 會話
第二種方法使用 SQLAlchemy ORM(物件關係對映),它允許將類對映到資料庫中的表,從而提供高階的、符合 Python 風格的介面。
示例
from sqlalchemy import create_engine, Column, Integer, String, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# Create a new engine instance
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
# Define a new table with a name, metadata, and several columns
class Sales(Base):
__tablename__ = 'sales'
id = Column(Integer, primary_key=True)
product = Column(String)
quantity = Column(Integer)
# Create the table
Base.metadata.create_all(engine)
# Prepare data
data = [
Sales(product='Apples', quantity=5),
Sales(product='Oranges', quantity=7),
Sales(product='Apples', quantity=3),
Sales(product='Bananas', quantity=8),
Sales(product='Apples', quantity=6),
Sales(product='Oranges', quantity=9),
]
# Add and commit data to the session
session.add_all(data)
session.commit()
# Create a select statement
stmt = session.query(Sales.product, func.sum(Sales.quantity).label('total_quantity')).group_by(Sales.product)
# Execute the statement
results = stmt.all()
for result in results:
print(result)
session.close()
解釋
在這種方法中,我們首先建立一個引擎來連線到資料庫。然後,我們使用 sessionmaker 定義會話工廠並例項化一個會話物件。接下來,我們使用 declarative_base() 為我們的表定義宣告一個基類,並使用 Sales 類定義表的結構。我們使用 Base.metadata.create_all(engine) 在資料庫中建立表。
為了執行分組和求和,我們使用 session.add_all(data) 將必要的資料新增到會話中,並使用 session.commit() 提交更改。我們使用 session.query 和 func.sum 建立帶分組和求和的 select 語句,並使用 stmt.all() 執行它。最後,我們處理結果並使用 session.close() 關閉會話。
結論
對 SQL 表中的列進行分組和求和是資料操作和分析中基本但必不可少的操作。SQLAlchemy 憑藉其易用性和類似 Python 的語法,彌合了 SQL 操作和 Python 程式設計之間的差距。根據上下文使用顯式會話或 ORM 會話的能力進一步增強了 SQLAlchemy 的吸引力。上面提到的兩種方法都可以根據需要進行調整,為使用 SQL 資料庫的 Python 使用者奠定堅實的基礎。請務必關閉會話以釋放資源。有了這些知識,您現在就可以使用 Python 中的 SQLAlchemy 執行 GroupBy 和 Sum 操作了。編碼愉快!
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP