Home  >  Article  >  Backend Development  >  How to Accurately Calculate Salary Sum with GORM?

How to Accurately Calculate Salary Sum with GORM?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 20:54:02118browse

How to Accurately Calculate Salary Sum with GORM?

Calculating Salary Sum using GORM

Getting the sum of a column, such as salary, from a table using GORM can be achieved efficiently. Here's a revised code example that should accomplish this task:

<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 SalaryResult struct { // Define a result structure
        TotalSalary int64 `json:"total_salary"`
    }

    query := "SELECT SUM(salary) AS total_salary FROM people"
    result := SalaryResult{} // Initialize the result structure

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

    fmt.Println("sum->", result)
    return c.JSON(http.StatusOK, result)
}</code>

In this revised code, we define a SalaryResult structure to represent the result of the query. We then use the Scan() method to scan the query result into this structure. Finally, we return the result containing the sum of salary column to the client.

The above is the detailed content of How to Accurately Calculate Salary Sum with GORM?. 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