postgresql - 如何正确分组 Postgres 数据

标签 postgresql go go-gorm

在 PostgreSQL 中,我有这样的表:

| QUESTION_TEXT                          | CATEGORY | AGREE_PERCENT | DISAGREE_PERCENT |
|----------------------------------------|----------|---------------|------------------|
| Do you support the President's policy? | Policy   | 50            | 50               |
| Do you support Democrats?              | Policy   | 32            | 68               |
| Do you support the Lannisters?         | Cinema   | 45            | 55               |
| Do you support Spielberg's work?       | Cinema   | 60            | 40               |

在我的 Go 应用程序中借助 gorm library我像这样向 PostgreSQL 数据库发出 SQL 请求:

type Entry struct {
     QuestionText string `json:"question_text"`
     Category string `json:"category"`
     AgreePercent float64 `json:"agree_percent"`
     DisagreePercent float64 `json:"disagree_percent"`
}

rows, _ := database.DBGORM.Raw("SELECT * FROM SPECIFICATION").Rows()

for rows.Next() {
     entry := &Entry{}

     if err = rows.Scan(&entry.QuestionText, & entry.Category,  &entry.AgreePercent, &entry.DisagreePercent); err != nil {
          utils.Logger().Println(err)   
     }
}

如何得到相似的结果?如您所见,数组中的每个对象都按 category 列中的值分组:

[
     {
          category: "Policy",
          questions: ["Do you support the President's policy?", "Do you support Democrats?"],
          series: [
               {
                    name: "Agree, %",
                    data: [50, 32]
               },
               {
                    name: "Disagree, %",
                    data: [50, 68]
               },
          ] 
     },
     {
          category: "Cinema",
          questions: ["Do you support the Lannisters?", "Do you support Spielberg's work?"],
          series: [
               {
                    name: "Agree, %",
                    data: [45, 60]
               },
               {
                    name: "Disagree, %",
                    data: [55, 40]
               },
          ] 
     },
]

最佳答案

好吧,我不能说这是优雅的方式,但最终我解决了我的任务:

// Create struct called "Series".
type Series struct {
    Name string `json:"name"`
    Data []float64 `json:"data"`
}

// Create struct called "Specification".
type Specification struct {
    Category string `json:"category"`
    Questions []string `json:"questions"`
    Series []Series `json:"series"`
}

// Initialize an array of struct.
var specifications []Specification

// Initialize several variables.
var catogoryName string
var arrayQuestionText []string
var arrayAgreePercent []float64
var arrayDisagreePercent []float64


for rows.Next() {
    // Check the change in the name of the category.
    if entry.Category == catogoryName {
        // Add new elements to arrays.
        arrayQuestionText = append(arrayQuestionText, entry.QuestionText)
        arrayDisagreePercent = append(arrayDisagreePercent, entry.DisagreePercent)
        arrayAgreePercent = append(arrayAgreePercent, entry.AgreePercent)
    } else {
        if len(catogoryName) > 0 {
            // Fill the struct with data.
            specification := Specification{
                Category: catogoryName,
                Questions: arrayQuestionText,
                Series: []Series{
                    {
                        Name: "Agree, %",
                        Data: arrayAgreePercent,
                    },
                    {
                        Name: "Disagree, %",
                        Data: arrayDisagreePercent,
                    },
                },
            }

            // Add new struct to array.
            specifications = append(specifications, specification)
        }
    }
    // Update data in arrays.
    catogoryName = entry.Category
    arrayQuestionText = nil
    arrayQuestionText = append(arrayQuestionText, entry.QuestionText)
    arrayDisagreePercent = nil
    arrayDisagreePercent = append(arrayDisagreePercent, entry.DisagreePercent)
    arrayAgreePercent = nil
    arrayAgreePercent = append(arrayAgreePercent, entry.AgreePercent)
}

关于postgresql - 如何正确分组 Postgres 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57146925/

相关文章:

sql - 在 FROM 子句中创建一个大的虚拟表

api - Google 存储桶签名 URL 403

go - 用Go编写的lambda API的设计

go - 如何访问 gorm.Model.ID?

sql - Postgres 中是否有与 Oracle 的 BITAND() 函数等效的函数?

sql - 随时间重复消除

postgresql - 第一次在协调器上初始化查找时 Druid Postgresql 语法错误

windows - GitHub 操作 : Run golint on wihdows

go - 如何将 Go 应用程序部署到 Bluemix?

go - 在 Golang 中处理 URL 中的动态参数