﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31566	Subquery in annotation is included by its alias and is not present in the SELECT	Gagaro	Simon Charette	"With the following queryset:

{{{
IndicatorValue.objects
    .values(""freight"")
    .annotate(
        has_top_loading=Exists(OrderItemResult.objects.order_by().filter(order_line__order__freight=OuterRef(""freight""), loading_arm__loading_type=LoadingArm.LOADING_TYPE_TOP,).values('pk')),
        start_time=Min(""datetime"")
    )
    .values('start_time')
}}}

I have the following error:

{{{
ProgrammingError: column ""has_top_loading"" does not exist
LINE 1: ...ROUP BY ""indicators_indicatorvalue"".""freight_id"", ""has_top_l...
}}}

The generated SQL is:

{{{
SELECT MIN(""indicators_indicatorvalue"".""datetime"") AS ""start_time""
FROM ""indicators_indicatorvalue""
GROUP BY ""indicators_indicatorvalue"".""freight_id"", ""has_top_loading""
}}}

`has_top_loading` is only mentioned in the `GROUP_BY` and not in the `SELECT`.

On Django 2.2, the same queryset generates the following SQL:

{{{
SELECT MIN(""indicators_indicatorvalue"".""datetime"") AS ""start_time""
FROM ""indicators_indicatorvalue""
GROUP BY ""indicators_indicatorvalue"".""freight_id"", (EXISTS(SELECT U0.""id"" FROM ""orders_orderitemresult"" U0 INNER JOIN ""loading_terminal_loadingarm"" U1 ON (U0.""loading_arm_id"" = U1.""id"") INNER JOIN ""orders_orderitem"" U2 ON (U0.""order_line_id"" = U2.""id"") INNER JOIN ""orders_order"" U3 ON (U2.""order_id"" = U3.""id"") WHERE (U1.""loading_type"" = TOP AND U3.""freight_id"" = (""indicators_indicatorvalue"".""freight_id""))))
}}}

"	Bug	closed	Database layer (models, ORM)	3.0	Release blocker	fixed			Ready for checkin	1	0	0	0	0	0
