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

How to Calculate Sum of a Column Using SQL and GORM?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 03:33:30319browse

How to Calculate Sum of a Column Using SQL and GORM?

Finding the Sum of Salary Column Using GORM

When querying a database table, it is often necessary to calculate aggregate functions such as the sum of a particular column. In GORM, this can be achieved using a combination of SQL query and Go data structures.

Unfortunately, the provided code attempts to use both a Golang struct and a SQL query, which can lead to errors. To get the sum of the salary column, follow the following steps:

  1. Define a Go data structure to hold the result:
<code class="go">type NResult struct {
    Sum int64
}</code>
  1. Create a function to execute the SQL query and store the result in the data structure:
<code class="go">func GetSalarySum() int64 {
    var result NResult
    db.Table("people").Select("SUM(salary) AS sum").Scan(&result)
    return result.Sum
}</code>

In this code, we use the Scan method to directly store the result in the NResult struct.

Example usage:

<code class="go">sum := GetSalarySum()
fmt.Println("Salary sum:", sum)</code>

The above is the detailed content of How to Calculate Sum of a Column Using SQL and 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