gorm/tests/group_by_test.go

71 lines
1.8 KiB
Go
Raw Normal View History

2020-05-23 18:50:48 +03:00
package tests_test
import (
"testing"
2020-06-02 05:34:50 +03:00
. "gorm.io/gorm/utils/tests"
2020-05-23 18:50:48 +03:00
)
func TestGroupBy(t *testing.T) {
var users = []User{{
Name: "groupby",
Age: 10,
Birthday: Now(),
2020-06-25 18:37:49 +03:00
Active: true,
2020-05-23 18:50:48 +03:00
}, {
Name: "groupby",
Age: 20,
Birthday: Now(),
}, {
Name: "groupby",
Age: 30,
Birthday: Now(),
2020-06-25 18:37:49 +03:00
Active: true,
2020-05-23 18:50:48 +03:00
}, {
Name: "groupby1",
Age: 110,
Birthday: Now(),
}, {
Name: "groupby1",
Age: 220,
Birthday: Now(),
2020-06-25 18:37:49 +03:00
Active: true,
2020-05-23 18:50:48 +03:00
}, {
Name: "groupby1",
Age: 330,
Birthday: Now(),
2020-06-25 18:37:49 +03:00
Active: true,
2020-05-23 18:50:48 +03:00
}}
if err := DB.Create(&users).Error; err != nil {
t.Errorf("errors happened when create: %v", err)
}
var name string
var total int
if err := DB.Model(&User{}).Select("name, sum(age)").Where("name = ?", "groupby").Group("name").Row().Scan(&name, &total); err != nil {
t.Errorf("no error should happen, but got %v", err)
}
if name != "groupby" || total != 60 {
t.Errorf("name should be groupby, but got %v, total should be 60, but got %v", name, total)
}
if err := DB.Model(&User{}).Select("name, sum(age) as total").Where("name LIKE ?", "groupby%").Group("name").Having("name = ?", "groupby1").Row().Scan(&name, &total); err != nil {
t.Errorf("no error should happen, but got %v", err)
}
if name != "groupby1" || total != 660 {
t.Errorf("name should be groupby, but got %v, total should be 660, but got %v", name, total)
}
2020-06-25 18:37:49 +03:00
var active bool
if err := DB.Model(&User{}).Select("name, active, sum(age)").Where("name = ? and active = ?", "groupby", true).Group("name").Group("active").Row().Scan(&name, &active, &total); err != nil {
t.Errorf("no error should happen, but got %v", err)
}
if name != "groupby" || active != true || total != 40 {
t.Errorf("group by two columns, name %v, age %v, active: %v", name, total, active)
}
2020-05-23 18:50:48 +03:00
}