How to perform aggregation and grouping in SQL queries with Go?

To perform aggregation and grouping in SQL queries with Go, you can use the database/sql package along with a SQL library such as go-sqlite3, go-mysql-driver, or lib/pq depending on the database you are using. Here's an example of how to perform aggregation and grouping in SQL queries with Go:

  1. Import the required packages:
import ( "database/sql" _ "github.com/go-sql-driver/mysql" // Import the MySQL driver // Other necessary packages )
  1. Connect to the database using database/sql:
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { log.Fatal(err) } defer db.Close()
  1. Write the SQL query with aggregation and grouping:
query := ` SELECT category, COUNT(*) as count FROM products GROUP BY category `
  1. Execute the query and handle the results:
rows, err := db.Query(query) if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var category string var count int err = row.Scan(&category, &count) if err != nil { log.Fatal(err) } fmt.Printf("Category: %s, Count: %d\n", category, count) }

Make sure to replace the database connection details, SQL query, and column names with your actual information. Additionally, handle any errors that may occur during the database connection, query execution, or result scanning.

Remember to add the necessary error handling, such as checking for errors returned by sql.Open, db.Query, row.Scan, and rows.Close.