@@ -132,11 +132,6 @@ public QueryRendererBuilder visitFromRoot(HqlParser.FromRootContext ctx) {
132132
133133 if (ctx .variable () != null ) {
134134 builder .appendExpression (visit (ctx .variable ()));
135-
136- } else {
137-
138- builder .append (TOKEN_AS );
139- builder .append (TOKEN_DOUBLE_UNDERSCORE );
140135 }
141136 } else if (ctx .subquery () != null ) {
142137
@@ -191,14 +186,26 @@ public QueryTokenStream visitSelectClause(HqlParser.SelectClauseContext ctx) {
191186 boolean usesDistinct = ctx .DISTINCT () != null ;
192187 QueryRendererBuilder nested = QueryRenderer .builder ();
193188 if (countProjection == null ) {
189+ QueryTokenStream selection = visit (ctx .selectionList ());
194190 if (usesDistinct ) {
195191
196192 nested .append (QueryTokens .expression (ctx .DISTINCT ()));
197- nested .append (getDistinctCountSelection (visit ( ctx . selectionList ()) ));
193+ nested .append (getDistinctCountSelection (selection ));
198194 } else {
199195
200196 // with CTE primary alias fails with hibernate (WITH entities AS (…) SELECT count(c) FROM entities c)
201- nested .append (containsCTE ? QueryTokens .token ("*" ) : QueryTokens .token (primaryFromAlias ));
197+ if (containsCTE ) {
198+ nested .append (QueryTokens .token ("*" ));
199+ } else {
200+
201+ if (selection .size () == 1 ) {
202+ nested .append (selection );
203+ } else if (primaryFromAlias != null ) {
204+ nested .append (QueryTokens .token (primaryFromAlias ));
205+ } else {
206+ nested .append (QueryTokens .token ("*" ));
207+ }
208+ }
202209 }
203210 } else {
204211 builder .append (QueryTokens .token (countProjection ));
@@ -249,6 +256,7 @@ public QueryRendererBuilder visitQueryOrder(HqlParser.QueryOrderContext ctx) {
249256 }
250257
251258 private QueryRendererBuilder visitSubQuerySelectClause (SelectClauseContext ctx , QueryRendererBuilder builder ) {
259+
252260 if (ctx .DISTINCT () != null ) {
253261 builder .append (QueryTokens .expression (ctx .DISTINCT ()));
254262 }
@@ -263,8 +271,13 @@ private QueryRendererBuilder getDistinctCountSelection(QueryTokenStream selectio
263271 CountSelectionTokenStream countSelection = CountSelectionTokenStream .create (selectionListbuilder );
264272
265273 if (countSelection .requiresPrimaryAlias ()) {
266- // constructor
267- nested .append (QueryTokens .token (primaryFromAlias ));
274+
275+ if (primaryFromAlias != null ) {
276+ // constructor
277+ nested .append (QueryTokens .token (primaryFromAlias ));
278+ } else {
279+ nested .append (countSelection .withoutConstructorExpression ());
280+ }
268281 } else {
269282 // keep all the select items to distinct against
270283 nested .append (selectionListbuilder );
0 commit comments