Hello, i am pulling data from a db in the form of :
client, month, sales
ACME Corp, 01, 7500
ABC Corp, 01, 2500
etc…
I now want to add in Go to an appropriate vehicle. But I am not sure what the best way to go froward would be, is a struct or a map of maps.
I tried so far the struct way but I must be missing something ?
type monthlytotal struct {
client string
month map[string]string
}
var months, clients, sales string
for result.Next() {
err := result.Scan(&months, &clients, &sales)
if err != nil {
log.Fatal(err)
}
c := new(monthlytotal)
c.client = clients
c.month = make(map[string]string)
c.month[months] = sales
}
Is that the best way, and how to now loop over all clients and access the map in order to print something like this ? :
Since each client would have several (month, sale) combinations, I think a good way to go about it would be a map[string][]struct. Where client is the key and a struct with month and sale would be the value. (According to how I understand your question)
Eg:
type monthlytotal struct{
month string
sale string
}
.
.
.
var clientMap = make(map[string][]monthlytotal)
var month, client, sale string
for result.Next() {
err := result.Scan(&month, &client, &sale)
if err != nil {
log.Fatal(err)
}
var out = monthlytotal{
month: month,
sale: sale,
}
clientMap[client] = append(clientMap[client], out)
}
for c, outSlice := range clientMap{
for _, v := range outSlice{
// c is your client, and v is each element of the slice
fmt.Println(c, v.month, v.sale)
}
}
Something like this should work. It’s been a while since I worked on db, but I think this would cut it. Let me know if there are any issues.