Skip to content

Commit a9dcd0b

Browse files
committed
Implemented support for group by without aggregate function
1 parent 36277e8 commit a9dcd0b

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/logsql/select.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,11 +1185,18 @@ func (v *selectTranslatorVisitor) buildStatsPipe(stmt *ast.SelectStatement, havi
11851185

11861186
if len(aggregates) == 0 {
11871187
if hasGroup {
1188-
return nil, false, &TranslationError{
1189-
Code: http.StatusBadRequest,
1190-
Message: "translator: GROUP BY requires aggregate expressions",
1188+
v.aggResults = make(map[string]string)
1189+
v.aggTempDeletes = nil
1190+
var pipe string
1191+
if len(groupFields) > 0 {
1192+
pipe = fmt.Sprintf("uniq by (%s)", strings.Join(groupFields, ", "))
1193+
} else {
1194+
pipe = "uniq"
11911195
}
1196+
pipes := append(preGroupPipes, pipe)
1197+
return pipes, true, nil
11921198
}
1199+
v.aggResults = nil
11931200
return nil, false, nil
11941201
}
11951202

@@ -2561,7 +2568,7 @@ func (v *selectTranslatorVisitor) buildProjectionPipes(columns []ast.SelectItem,
25612568
if len(renamePairs) > 0 {
25622569
pipes = append(pipes, "rename "+strings.Join(renamePairs, ", "))
25632570
}
2564-
if len(fields) > 0 && !aggregated {
2571+
if len(fields) > 0 && (!aggregated || len(v.aggResults) == 0) {
25652572
pipes = append(pipes, "fields "+strings.Join(fields, ", "))
25662573
}
25672574
return pipes, fields, nil

lib/logsql/select_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,11 @@ SELECT * FROM logs WHERE level = 'warn'`,
408408
sql: "SELECT service, SUM(1) AS total FROM logs GROUP BY service",
409409
expected: "* | format 1 as __const_1 | stats by (service) sum(__const_1) total",
410410
},
411+
{
412+
name: "group by without aggregates",
413+
sql: "SELECT kubernetes.container_name FROM logs GROUP BY kubernetes.container_name",
414+
expected: "* | uniq by (kubernetes.container_name) | fields kubernetes.container_name",
415+
},
411416
{
412417
name: "having aggregate constant",
413418
sql: "SELECT SUM(1) AS \"cnt_slack_079B451E84304DF1AAA4188E26F02806_ok\" FROM logs HAVING COUNT(1) > 0",

0 commit comments

Comments
 (0)