3

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

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

4

3 回答 3

4

你的代码的结果是什么?

好的,如果您需要 SQL 中的总和结果。您可以scan在没有结构声明的情况下像这样使用。

var sum int
db.Table("table").Select("sum(column)").Row().Scan(&sum)
return sum
于 2019-09-17T10:02:06.357 回答
3

您仍在使用structgolang 并使用asinSQL

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
}
于 2019-12-13T07:48:57.993 回答
0

您不需要使用完整的 SQL 查询语法。试着改成这个

rows, err := db.Table("people").Select("sum(salary) as total").Rows()
for rows.Next() {
    ...
}
于 2018-12-13T10:27:26.163 回答