dongmei8760 2019-07-22 13:15
浏览 175
已采纳

如何正确分组Postgres数据

In PostgreSQL, I have such table:

| 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               |

In my Go application with the help of gorm library I make SQL request to PostgreSQL database like that:

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)   
     }
}

How to get a similar result? As you can see each object inside the array is grouped by value in the category column:

[
     {
          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]
               },
          ] 
     },
]
  • 写回答

1条回答 默认 最新

  • drwxg62286 2019-07-23 04:42
    关注

    Well, I can't say that it's elegant way, but finally I solve my task:

    // 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路