@@ -127,11 +127,6 @@ public QueryRendererBuilder visitFromRoot(HqlParser.FromRootContext ctx) {
127127
128128 if (ctx .variable () != null ) {
129129 builder .appendExpression (visit (ctx .variable ()));
130-
131- } else {
132-
133- builder .append (TOKEN_AS );
134- builder .append (TOKEN_DOUBLE_UNDERSCORE );
135130 }
136131 } else if (ctx .subquery () != null ) {
137132
@@ -186,14 +181,26 @@ public QueryTokenStream visitSelectClause(HqlParser.SelectClauseContext ctx) {
186181 boolean usesDistinct = ctx .DISTINCT () != null ;
187182 QueryRendererBuilder nested = QueryRenderer .builder ();
188183 if (countProjection == null ) {
184+ QueryTokenStream selection = visit (ctx .selectionList ());
189185 if (usesDistinct ) {
190186
191187 nested .append (QueryTokens .expression (ctx .DISTINCT ()));
192- nested .append (getDistinctCountSelection (visit ( ctx . selectionList ()) ));
188+ nested .append (getDistinctCountSelection (selection ));
193189 } else {
194190
195191 // with CTE primary alias fails with hibernate (WITH entities AS (…) SELECT count(c) FROM entities c)
196- nested .append (containsCTE ? QueryTokens .token ("*" ) : QueryTokens .token (primaryFromAlias ));
192+ if (containsCTE ) {
193+ nested .append (QueryTokens .token ("*" ));
194+ } else {
195+
196+ if (selection .size () == 1 ) {
197+ nested .append (selection );
198+ } else if (primaryFromAlias != null ) {
199+ nested .append (QueryTokens .token (primaryFromAlias ));
200+ } else {
201+ nested .append (QueryTokens .token ("*" ));
202+ }
203+ }
197204 }
198205 } else {
199206 builder .append (QueryTokens .token (countProjection ));
@@ -244,6 +251,7 @@ public QueryRendererBuilder visitQueryOrder(HqlParser.QueryOrderContext ctx) {
244251 }
245252
246253 private QueryRendererBuilder visitSubQuerySelectClause (SelectClauseContext ctx , QueryRendererBuilder builder ) {
254+
247255 if (ctx .DISTINCT () != null ) {
248256 builder .append (QueryTokens .expression (ctx .DISTINCT ()));
249257 }
@@ -258,8 +266,13 @@ private QueryRendererBuilder getDistinctCountSelection(QueryTokenStream selectio
258266 CountSelectionTokenStream countSelection = CountSelectionTokenStream .create (selectionListbuilder );
259267
260268 if (countSelection .requiresPrimaryAlias ()) {
261- // constructor
262- nested .append (QueryTokens .token (primaryFromAlias ));
269+
270+ if (primaryFromAlias != null ) {
271+ // constructor
272+ nested .append (QueryTokens .token (primaryFromAlias ));
273+ } else {
274+ nested .append (countSelection .withoutConstructorExpression ());
275+ }
263276 } else {
264277 // keep all the select items to distinct against
265278 nested .append (selectionListbuilder );
0 commit comments