I am using PostgreSQL and golang to write a backend. I am having a problem to get a sum of salary column.
This is my code:
func GetSalarySum(c echo.Context) error {
db, err := gorm.Open("postgres", "host=localhost port=5433 user=postgres dbname=testone password=root sslmode=disable")
checkError(err)
defer db.Close()
type UpdatedAddress struct {
City string `json:"city;"`
State string `json:"state;"`
Pin string `json:"pin;"`
}
type UpdatedContact struct {
ID uint `json:"id;"`
Mobile string `json:"mobile;"`
Email string `json:"email;"`
}
type NewPerson struct {
ID int `gorm:"primary_key:true;"`
Firstname string `json:"firstname;"`
Lastname string `json:"lastname;"`
Gender string `json:"gender;"`
Salary uint `json:salary;`
Age uint `json:"age"`
Address UpdatedAddress `json:"address"`
Contact UpdatedContact `json:"contact"`
}
// var n []NewPerson
n := new(NewPerson)
if err := c.Bind(n); err != nil {
fmt.Println(err)
return err
}
// var sum uint
query := "SELECT SUM(salary) FROM people"
if err := db.Table("people").Select(query).Rows().Error; err != nil {
fmt.Println("error->", err)
}
fmt.Println("sum->", n)
return c.JSON(http.StatusOK, n)
} //SELECT SUM(salary) FROM people
..............................
you still using struct
in golang and using as
in SQL
type NResult struct {
N int64 //or int ,or some else
}
func SumSame() int64 {
var n NResult
db.Table("table").Select("sum(click) as n").Scan(&n)
return n.N
}
What is result of your code ?
Okay, If you need result of sum in SQL. You can use scan
like this without struct declaration.
var sum int
db.Table("table").Select("sum(column)").Row().Scan(&sum)
return sum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With