@@ -53,6 +53,14 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
53
53
writeComment (q , buf )
54
54
writeCTEs (q , buf , & args )
55
55
56
+ hasHaving := len (q .having ) != 0
57
+ hasGroupBy := len (q .groupBy ) != 0
58
+ hasSimpleCount := q .count && ! hasHaving && ! hasGroupBy
59
+ hasComplexCount := q .count && (hasHaving || hasGroupBy )
60
+ if hasComplexCount {
61
+ buf .WriteString ("SELECT COUNT(*) FROM (" )
62
+ }
63
+
56
64
buf .WriteString ("SELECT " )
57
65
58
66
if q .dialect .UseTopClause {
@@ -61,7 +69,7 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
61
69
}
62
70
}
63
71
64
- if q . count {
72
+ if hasSimpleCount {
65
73
buf .WriteString ("COUNT(" )
66
74
}
67
75
@@ -70,28 +78,28 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
70
78
hasDistinct := q .distinct != ""
71
79
if hasDistinct {
72
80
buf .WriteString ("DISTINCT " )
73
- if q . count {
81
+ if hasSimpleCount {
74
82
buf .WriteString ("(" )
75
83
}
76
84
buf .WriteString (q .distinct )
77
- if q . count {
85
+ if hasSimpleCount {
78
86
buf .WriteString (")" )
79
87
}
80
- } else if hasJoins && hasSelectCols && ! q . count {
88
+ } else if hasJoins && hasSelectCols && ! hasSimpleCount {
81
89
selectColsWithAs := writeAsStatements (q )
82
90
// Don't identQuoteSlice - writeAsStatements does this
83
91
buf .WriteString (strings .Join (selectColsWithAs , ", " ))
84
92
} else if hasSelectCols {
85
93
buf .WriteString (strings .Join (strmangle .IdentQuoteSlice (q .dialect .LQ , q .dialect .RQ , q .selectCols ), ", " ))
86
- } else if hasJoins && ! q . count {
94
+ } else if hasJoins && ! hasSimpleCount {
87
95
selectColsWithStars := writeStars (q )
88
96
buf .WriteString (strings .Join (selectColsWithStars , ", " ))
89
97
} else {
90
98
buf .WriteByte ('*' )
91
99
}
92
100
93
101
// close SQL COUNT function
94
- if q . count {
102
+ if hasSimpleCount {
95
103
buf .WriteByte (')' )
96
104
}
97
105
@@ -133,6 +141,9 @@ func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
133
141
134
142
writeModifiers (q , buf , & args )
135
143
144
+ if hasComplexCount {
145
+ buf .WriteByte (')' )
146
+ }
136
147
buf .WriteByte (';' )
137
148
return buf , args
138
149
}
0 commit comments