我想得到一个数据透视表,其值是code/name/plan/actual/。
当尝试执行下面的代码时,当执行union_all()时,我们得到一个没有subquery()方法的CompoundSelect对象。应该如何重写查询以获得期望的结果?
meta = request.sa.base.metadata
classifier_table = Table('classifier', meta, autoload=True,
autoload_with=request.sa.engine)
plan_table = Table('revenueplan', meta, autoload=True,
autoload_with=request.sa.engine)
fact_table = Table('revenuefact', meta, autoload=True,
autoload_with=request.sa.engine)
_base_classifier_columns = [
classifier_table.c.id.label('id'),
classifier_table.c.full_name.label('name'),
classifier_table.c.code.label('code')
]
_mock_null = literal_column(text='0')
_mock_null_plan = _mock_null.label(name='plan')
_mock_null_fact = _mock_null.label(name='fact')
_mock_at_start_of_year = datetime(datetime.now().year, 1, 1)
_mock_today = datetime.now()
_sum_plan = func.sum(plan_table.c.value).label('plan')
_sum_fact = func.sum(fact_table.c.value).label('fact')
_join_plan_w_classifier = join(classifier_table, plan_table,
classifier_table.c.id == plan_table.c.classifier_id)
_join_fact_w_classifier = join(classifier_table, fact_table,
classifier_table.c.id == fact_table.c.classifier_id)
_plan_1st = select(
_base_classifier_columns + [
plan_table.c.value.label('plan'), _mock_null_fact
]).select_from(_join_plan_w_classifier)\
.where(between(plan_table.c.date, _mock_at_start_of_year, _mock_today))\
.group_by(classifier_table.c.id)
_fact_1st = select(
_base_classifier_columns + [
_mock_null_plan, fact_table.c.value.label('fact')
]).select_from(_join_fact_w_classifier)\
.where(between(fact_table.c.date, _mock_at_start_of_year, _mock_today))\
.group_by(classifier_table.c.id)
_union_year = union_all(_plan_1st, _fact_1st)
_sub_union_year = _union_year.subquery('_sub_union_year')
# ^
# Здесь ошибка,
stmt = select([
_sub_union_year.c.id,
_sub_union_year.c.name,
_sub_union_year.c.code,
func.Sum(_sub_union_year.c.plan).label('plan'),
func.Sum(_sub_union_year.c.fact).label('fact')
]).where.select_from(_sub_union_year).group_by(_sub_union_year.c.id)
您可以调用.cte()方法来请求选择的结果。
应删除主要选择中按 id 分组。