SQLAlchemy:内部分组依据不同
SQLAlchemy: Distinct inside group by
我想在 group_by 查询中使用 distinct,例如:
session.query(Product.attribute_x, func.min(Product.price), distinct(Product.color)). group_by(Product.attribute_x)
也就是说,对于 attribute_x 的每个值,我想找到最低价格和所有可用的颜色。
我似乎无法在 SQLAlchemy 中以这种方式使用 distinct。谁能建议一种有效的方法来识别 attribute_x 的每个值的不同颜色(无需为 attribute_x 的每个值创建新查询)?
我在 PostgreSQL 上使用 SQLALchemy 1.3.4。
使用array_agg
:
from sqlalchemy.dialects.postgresql import array_agg
session.query(Product.attribute_x,
func.min(Product.price),
array_agg(distinct(Product.color))).\
group_by(Product.attribute_x)
在这种情况下,func.array_agg()
也可以。 Postgresql 方言特定形式只是确保 return 类型被理解为 Postgresql ARRAY
而不是通用类型,以防您想使用任何数组运算符等
我想在 group_by 查询中使用 distinct,例如:
session.query(Product.attribute_x, func.min(Product.price), distinct(Product.color)). group_by(Product.attribute_x)
也就是说,对于 attribute_x 的每个值,我想找到最低价格和所有可用的颜色。
我似乎无法在 SQLAlchemy 中以这种方式使用 distinct。谁能建议一种有效的方法来识别 attribute_x 的每个值的不同颜色(无需为 attribute_x 的每个值创建新查询)?
我在 PostgreSQL 上使用 SQLALchemy 1.3.4。
使用array_agg
:
from sqlalchemy.dialects.postgresql import array_agg
session.query(Product.attribute_x,
func.min(Product.price),
array_agg(distinct(Product.color))).\
group_by(Product.attribute_x)
在这种情况下,func.array_agg()
也可以。 Postgresql 方言特定形式只是确保 return 类型被理解为 Postgresql ARRAY
而不是通用类型,以防您想使用任何数组运算符等