【问题标题】:In SQLAlchemy how to merge multiple rows into one by converting unique column values into comma separated string?在 SQLAlchemy 中,如何通过将唯一列值转换为逗号分隔的字符串来将多行合并为一行?
【发布时间】:2021-12-28 16:55:53
【问题描述】:
示例表
| Invoice Number |
Invoice Date |
Item Name |
| 1001 |
12 Jul 21 |
Foo |
| 1002 |
10 Jun 21 |
Baz |
| 1001 |
12 Jul 21 |
Bar |
| 1002 |
10 Jun 21 |
Spam |
| 1001 |
12 Jul 21 |
Eggs |
如何编写 sqlalchemy ORM 查询以获取以下格式的这些数据:
| Invoice Number |
Invoice Date |
Items |
| 1001 |
12 Jul 21 |
Foo,Bar, Eggs |
| 1002 |
10 Jun 21 |
Baz, Spam |
我正在后端连接到一个 sql server 数据库。
【问题讨论】:
标签:
python
sql-server
sqlalchemy
【解决方案1】:
我没有用 SQL-Server 测试过,但我认为你可以使用 string_agg 函数。
更简单的版本,如果您可以在逗号分隔列表中使用重复值:
from sqlalchemy import func
from sqlalchemy.sql.elements import literal_column
result = session.query(
Table.invoice_number,
Table.invoice_date,
func.string_agg(Table.item_name, literal_column("','"))
).group_by(
Table.invoice_number,
Table.invoice_date
).all()
而且,如果您需要避免重复值:
sub_query = session.query(Table).distinct().subquery()
result = session.query(
sub_query.c.invoice_number,
sub_query.c.invoice_date,
func.string_agg(sub_query.c.item_name, literal_column("','"))
).\
select_from(sub_query).\
group_by(
sub_query.c.invoice_number,
sub_query.c.invoice_date
).all()