My raw query is
SELECT
at."category" AS "category",
at."month" AS "month",
sum(at.price_aft_discount) as "sum",
sum(at.qty_ordered) as "sum2"
FROM
all_trans at
GROUP BY
at."category",
at."month"
ORDER BY
at."category" ASC,
at."month" asc
When executing above query in DBeaver, the sum columns give warning: sum: numeric(131089,0) (Read-only: No corresponding table column)
. Same warning is given for sum2
My code to query save the result in Go using Gorm is:
type ATQueryResult struct {
category string `gorm:"column:category"`
month string `gorm:"column:month"`
sum float32 `gorm:"column:sum"`
sum2 float32 `gorm:"column:sum2"`
}
queryString := ... // same as above
var result []ATQueryResult
db.Table(model.TableAllTrans).Raw(queryString).Find(&result)
fmt.Println(result[3])
But the issue is, all result[i].sum
and result[i].sum2
is 0-zero
. I can see the actual sum number (which is all non-zero) when querying live on DBeaver, albeit with the above warning. But when I tried to scan the query result on to result
, all the sum values are 0.
CodePudding user response:
The fields must be exported for gorm (or whatever it leverages under the hood) to be able to populate them. Try using:
type ATQueryResult struct {
Category string `gorm:"column:category"`
Month string `gorm:"column:month"`
Sum float32 `gorm:"column:sum"`
Sum2 float32 `gorm:"column:sum2"`
}