@@ -132,11 +132,6 @@ public QueryRendererBuilder visitFromRoot(HqlParser.FromRootContext ctx) {
132
132
133
133
if (ctx .variable () != null ) {
134
134
builder .appendExpression (visit (ctx .variable ()));
135
-
136
- } else {
137
-
138
- builder .append (TOKEN_AS );
139
- builder .append (TOKEN_DOUBLE_UNDERSCORE );
140
135
}
141
136
} else if (ctx .subquery () != null ) {
142
137
@@ -191,14 +186,26 @@ public QueryTokenStream visitSelectClause(HqlParser.SelectClauseContext ctx) {
191
186
boolean usesDistinct = ctx .DISTINCT () != null ;
192
187
QueryRendererBuilder nested = QueryRenderer .builder ();
193
188
if (countProjection == null ) {
189
+ QueryTokenStream selection = visit (ctx .selectionList ());
194
190
if (usesDistinct ) {
195
191
196
192
nested .append (QueryTokens .expression (ctx .DISTINCT ()));
197
- nested .append (getDistinctCountSelection (visit ( ctx . selectionList ()) ));
193
+ nested .append (getDistinctCountSelection (selection ));
198
194
} else {
199
195
200
196
// 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
+ }
202
209
}
203
210
} else {
204
211
builder .append (QueryTokens .token (countProjection ));
@@ -249,6 +256,7 @@ public QueryRendererBuilder visitQueryOrder(HqlParser.QueryOrderContext ctx) {
249
256
}
250
257
251
258
private QueryRendererBuilder visitSubQuerySelectClause (SelectClauseContext ctx , QueryRendererBuilder builder ) {
259
+
252
260
if (ctx .DISTINCT () != null ) {
253
261
builder .append (QueryTokens .expression (ctx .DISTINCT ()));
254
262
}
@@ -263,8 +271,13 @@ private QueryRendererBuilder getDistinctCountSelection(QueryTokenStream selectio
263
271
CountSelectionTokenStream countSelection = CountSelectionTokenStream .create (selectionListbuilder );
264
272
265
273
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
+ }
268
281
} else {
269
282
// keep all the select items to distinct against
270
283
nested .append (selectionListbuilder );
0 commit comments