Home >Backend Development >Golang >How to Retrieve the Sum of a Column Value Using GORM and Scan?

How to Retrieve the Sum of a Column Value Using GORM and Scan?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 23:08:30982browse

How to Retrieve the Sum of a Column Value Using GORM and Scan?

Retrieving Sum of Salary Column using GORM

In your code, you attempt to retrieve the sum of the salary column from a Postgres table named "people" using GORM. However, your current approach has some limitations.

To correctly retrieve the sum of the salary column, it's recommended to use GORM's Scan function instead of manually constructing a SQL query. This approach allows you to define a struct that represents the result you want to retrieve.

Example:

<code class="go">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 SalarySum struct {
        Sum uint `gorm:"column:sum"`
    }

    var salarySum SalarySum
    if err := db.Table("people").Select("SUM(salary) AS sum").Scan(&salarySum).Error; err != nil {
        fmt.Println("error->", err)
    }

    return c.JSON(http.StatusOK, salarySum)
}</code>

In this code:

  • The SalarySum struct defines the expected result of the query. It contains a single field "Sum" of type uint.
  • The db.Table("people").Select("SUM(salary) AS sum") line selects the sum of the salary column and aliases it as "sum" in the result.
  • The Scan(&salarySum) part scans the result into the salarySum struct.

This updated code should correctly retrieve and return the sum of the salary column from the "people" table.

The above is the detailed content of How to Retrieve the Sum of a Column Value Using GORM and Scan?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn