From f159d05209d0018e492b9273e508c22a75523331 Mon Sep 17 00:00:00 2001 From: huydx Date: Mon, 18 Jul 2016 16:43:19 +0900 Subject: [PATCH] Support count distinct --- main.go | 5 +++++ scope.go | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/main.go b/main.go index 04f39228..f34458c5 100644 --- a/main.go +++ b/main.go @@ -298,6 +298,11 @@ func (s *DB) Count(value interface{}) *DB { return s.NewScope(s.Value).count(value).db } +// CountDistinct get how many distinct records for a model +func (s *DB) CountDistinct(value interface{}, columnName string) *DB { + return s.NewScope(s.Value).countDistinct(value, columnName).db +} + // Related get related associations func (s *DB) Related(value interface{}, foreignKeys ...string) *DB { return s.clone().NewScope(s.Value).related(value, foreignKeys...).db diff --git a/scope.go b/scope.go index 974ff035..5c03b3bc 100644 --- a/scope.go +++ b/scope.go @@ -921,6 +921,13 @@ func (scope *Scope) count(value interface{}) *Scope { return scope } +func (scope *Scope) countDistinct(value interface{}, column string) *Scope { + scope.Search.Select(fmt.Sprintf("count(%s)", column)) + scope.Search.countingQuery = true + scope.Err(scope.row().Scan(value)) + return scope +} + func (scope *Scope) typeName() string { typ := scope.IndirectValue().Type()