Home  >  Article  >  Backend Development  >  How to Calculate Sum of a Column Using GORM and Scan in Golang?

How to Calculate Sum of a Column Using GORM and Scan in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 02:31:29521browse

How to Calculate Sum of a Column Using GORM and Scan in Golang?

Calculating Sum of Salary Column in a GORM Table

Working with relational databases like PostgreSQL using Golang often involves retrieving aggregate values. In this case, calculating the sum of a column, such as the salary column, is a common task.

Initial Code and Problem

The code provided attempts to calculate the sum of the salary column from the 'people' table but encounters an error. It uses the SELECT statement with SUM(salary) to retrieve the result and binds the value to the NewPerson struct. However, this approach is incorrect since NewPerson does not have a salary field, and the query is attempting to map the result directly to the struct.

Revised Code using Scan

To fix this issue, a different approach is needed. Golang provides the Scan function, which allows developers to retrieve the results of a query and map them to a custom data structure. Here's a revised version of the code that uses Scan:

<code class="go">type NResult struct {
    Salary int64 // or int, depending on the data type
}

func GetSalarySum(c echo.Context) error {
    db, err := gorm.Open("postgres", "...")
    checkError(err)
    defer db.Close()

    query := "SELECT SUM(salary) FROM people"

    var result NResult
    if err := db.Table("people").Raw(query).Scan(&result).Error; err != nil {
        fmt.Println("error->", err)
    }

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

In this code, we define a custom struct NResult with a single Salary field of type int64 or int, depending on the data type of the salary column. We use the Raw method to execute the SELECT SUM(salary) FROM people query directly, and the Scan function to retrieve the result and map it to the NResult struct.

This revised code correctly retrieves the sum of the salary column and returns it as a JSON response.

The above is the detailed content of How to Calculate Sum of a Column Using GORM and Scan in Golang?. 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