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

Mary-Kate Olsen
Release: 2024-10-24 03:33:30
Original
247 people have browsed it

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!