From fd15156d399274bcf281ac25ca0536075abd637a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 11 Feb 2018 09:16:10 +0800 Subject: [PATCH] Fix Count in mssql for SQL with group --- query_test.go | 9 +++++++++ scope.go | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/query_test.go b/query_test.go index 98721800..882fd611 100644 --- a/query_test.go +++ b/query_test.go @@ -430,6 +430,15 @@ func TestCount(t *testing.T) { if count1 != 1 || count2 != 3 { t.Errorf("Multiple count in chain") } + + var count3 int + if err := DB.Model(&User{}).Where("name in (?)", []string{user2.Name, user2.Name, user3.Name}).Group("id").Count(&count3).Error; err != nil { + t.Errorf("Not error should happen, but got %v", err) + } + + if count3 != 2 { + t.Errorf("Should get correct count, but got %v", count3) + } } func TestNot(t *testing.T) { diff --git a/scope.go b/scope.go index 63bf618f..ae98d251 100644 --- a/scope.go +++ b/scope.go @@ -951,8 +951,8 @@ func (scope *Scope) pluck(column string, value interface{}) *Scope { func (scope *Scope) count(value interface{}) *Scope { if query, ok := scope.Search.selects["query"]; !ok || !countingQueryRegexp.MatchString(fmt.Sprint(query)) { if len(scope.Search.group) != 0 { - scope.Search.Select("count(*) FROM ( SELECT count(*) ") - scope.Search.group += " ) AS count" + scope.Search.Select("count(*) FROM ( SELECT count(*) as name ") + scope.Search.group += " ) AS count_table" } else { scope.Search.Select("count(*)") }