4

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

..............................

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
gauravsbagul
  • 79
  • 1
  • 2
  • 8

3 Answers3

5

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
updogliu
  • 6,066
  • 7
  • 37
  • 50
PePoDev
  • 61
  • 1
  • 6
5

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
}
cakazies
  • 59
  • 1
  • 4
1

You do not need to use full SQL query syntaxis. Try to change to this

rows, err := db.Table("people").Select("sum(salary) as total").Rows()
for rows.Next() {
    ...
}
Maxim
  • 2,233
  • 6
  • 16