Skip to content

Commit

Permalink
Merge pull request #1398 from renom/master
Browse files Browse the repository at this point in the history
Count from subquery if query uses HAVING or GROUP BY
  • Loading branch information
stephenafamo authored Oct 23, 2024
2 parents bc92201 + cb3a21b commit 540d7a2
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions queries/query_builders.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
writeComment(q, buf)
writeCTEs(q, buf, &args)

hasHaving := len(q.having) != 0
hasGroupBy := len(q.groupBy) != 0
hasSimpleCount := q.count && !hasHaving && !hasGroupBy
hasComplexCount := q.count && (hasHaving || hasGroupBy)
if hasComplexCount {
buf.WriteString("SELECT COUNT(*) FROM (")
}

buf.WriteString("SELECT ")

if q.dialect.UseTopClause {
Expand All @@ -61,7 +69,7 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
}
}

if q.count {
if hasSimpleCount {
buf.WriteString("COUNT(")
}

Expand All @@ -70,28 +78,28 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
hasDistinct := q.distinct != ""
if hasDistinct {
buf.WriteString("DISTINCT ")
if q.count {
if hasSimpleCount {
buf.WriteString("(")
}
buf.WriteString(q.distinct)
if q.count {
if hasSimpleCount {
buf.WriteString(")")
}
} else if hasJoins && hasSelectCols && !q.count {
} else if hasJoins && hasSelectCols && !hasSimpleCount {
selectColsWithAs := writeAsStatements(q)
// Don't identQuoteSlice - writeAsStatements does this
buf.WriteString(strings.Join(selectColsWithAs, ", "))
} else if hasSelectCols {
buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.dialect.LQ, q.dialect.RQ, q.selectCols), ", "))
} else if hasJoins && !q.count {
} else if hasJoins && !hasSimpleCount {
selectColsWithStars := writeStars(q)
buf.WriteString(strings.Join(selectColsWithStars, ", "))
} else {
buf.WriteByte('*')
}

// close SQL COUNT function
if q.count {
if hasSimpleCount {
buf.WriteByte(')')
}

Expand Down Expand Up @@ -133,6 +141,9 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {

writeModifiers(q, buf, &args)

if hasComplexCount {
buf.WriteByte(')')
}
buf.WriteByte(';')
return buf, args
}
Expand Down

0 comments on commit 540d7a2

Please sign in to comment.