在子查询peewee上选择

时间:2018-10-03 15:46:01

标签: subquery peewee

我想知道是否可以对sub_query执行select()。 我可以用任何peewee.Model加入sub_query。但是,当我编写sub_query时,我只想与列

分组

e.g. sub_query.select(sub_query.c.column_1, fn.COUNT(sub_query.c.column2)alias('col2_count')).group_by(sub_query.c.column_1)

查询未嵌套,并且出现SQL语法错误。

(无法显示代码) (我在sub_query上完成了alias())

修改

示例:

class Product(Model):
    id = PrimaryKeyField()
    name = CharField()
    created_date = DateField()


class Part(Model):
    id = PrimaryKeyField()
    product = ForeignKeyField(Product)
    name = CharField()


class ProductError(Model):
    id = PrimaryKeyField()
    product = ForeignKeyField(Product)
    note = CharField()

class PartError(Model):
    id = PrimaryKeyField()
    part = ForeignKeyField(Part)
    error = ForeignKeyField(ErrorMaster)

此处产品可能有一般错误, 零件可能有特定的错误,这些错误已在ErrorMaster中预定义

我只想知道对总产品日期有误的产品数量。 (错误是产品错误或任何部分的错误)

所以sub_query类似于

sub_q = Product.select(
                Product.created_date,
                Product.id.alias('product_id'),
                fn.IF(# checks if product has error
                    ProductError.is_null(True),  if no product error check part error
                    fn.IF(fn.COUNT(PartError.id) == 0, 0, 1),  # checks if error count > 0 then there is error in part
                    1
                ).alias('is_error')
            ).join(Part, on=Product.id == Part.product)
            .join(ProductError, JOIN_LEFT_OUTER, on=Product.id == ProductError.product)
            .join(PartError, JOIN_LEFT_OUTER, on=PartError.part == Part.id)
            .where(Product.created_date.between(from_date, to_date))
            .group_by(Product.id).alias('some_alias')
# below does not work but I can do this in sql
query = sub_q.select(sub_q.c.created_date,
                 fn.COUNT(sub_q.c.product_id).alias('total_products'),
        fn.SUM(sub_q.c.is_error).alias('product_with_errors'))
             .group_by(sub_q.c.created_date)

0 个答案:

没有答案