Home >Backend Development >Golang >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:
<code class="go">type NResult struct { Sum int64 }</code>
<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!