dongtanliefang8765 2018-12-13 08:42
浏览 95

如何从表GORM中获取薪水总额列

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

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

  • 写回答

2条回答 默认 最新

  • 普通网友 2018-12-13 10:27
    关注

    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() {
        ...
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化