@@ -127,11 +127,6 @@ public QueryRendererBuilder visitFromRoot(HqlParser.FromRootContext ctx) {
127
127
128
128
if (ctx .variable () != null ) {
129
129
builder .appendExpression (visit (ctx .variable ()));
130
-
131
- } else {
132
-
133
- builder .append (TOKEN_AS );
134
- builder .append (TOKEN_DOUBLE_UNDERSCORE );
135
130
}
136
131
} else if (ctx .subquery () != null ) {
137
132
@@ -186,14 +181,26 @@ public QueryTokenStream visitSelectClause(HqlParser.SelectClauseContext ctx) {
186
181
boolean usesDistinct = ctx .DISTINCT () != null ;
187
182
QueryRendererBuilder nested = QueryRenderer .builder ();
188
183
if (countProjection == null ) {
184
+ QueryTokenStream selection = visit (ctx .selectionList ());
189
185
if (usesDistinct ) {
190
186
191
187
nested .append (QueryTokens .expression (ctx .DISTINCT ()));
192
- nested .append (getDistinctCountSelection (visit ( ctx . selectionList ()) ));
188
+ nested .append (getDistinctCountSelection (selection ));
193
189
} else {
194
190
195
191
// 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
+ }
197
204
}
198
205
} else {
199
206
builder .append (QueryTokens .token (countProjection ));
@@ -244,6 +251,7 @@ public QueryRendererBuilder visitQueryOrder(HqlParser.QueryOrderContext ctx) {
244
251
}
245
252
246
253
private QueryRendererBuilder visitSubQuerySelectClause (SelectClauseContext ctx , QueryRendererBuilder builder ) {
254
+
247
255
if (ctx .DISTINCT () != null ) {
248
256
builder .append (QueryTokens .expression (ctx .DISTINCT ()));
249
257
}
@@ -258,8 +266,13 @@ private QueryRendererBuilder getDistinctCountSelection(QueryTokenStream selectio
258
266
CountSelectionTokenStream countSelection = CountSelectionTokenStream .create (selectionListbuilder );
259
267
260
268
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
+ }
263
276
} else {
264
277
// keep all the select items to distinct against
265
278
nested .append (selectionListbuilder );
0 commit comments