Retrieving distinct values

Report a typo

Lena has a Go program that creates an in-memory SQLite database with the employees table that has records of all the employees in her company:

sqlite3 database

Now she wants to perform the following tasks:

  1. Retrieve only the different/unique title values from the employees table sorted in descending order, then save them in the jobTitles slice and print the contents of the jobTitles slice.
  2. Retrieve only the different/unique department values from the employees table sorted in ascending order, then save them in the departments slice and print the contents of the departments slice.

Lena has already created the Employee model struct, declared the jobTitles and departments slices, and written the statements to print the slices. Your task is to help her write the additional required code to perform the two tasks mentioned above.

Write a program in Go
package main

import (
"fmt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
)

type Employee struct { // Model for the `employees` table
gorm.Model
Name string
LastName string
Title string
Department string
Address string
}

func main() {
db := createDB() // DO NOT delete this line! it creates the in-memory database

var jobTitles, departments []string
// Retrieve all unique/different `title` values sorted in descending order below:
result := db.Model(&Employee{}).?("?").Order("?").Find(&?)
if result.Error != nil {
log.Fatalf("cannot retrieve unique titles: %v", result.Error)
}

// Retrieve all unique/different `department` values sorted in ascending order below:
result = ?
if result.Error != nil {
log.Fatalf("cannot retrieve unique departments: %v", result.Error)
}

// DO NOT delete the code block below! — it prints the results of the above queries:
fmt.Printf("%v\n", jobTitles)
___

Create a free account to access the full topic