doujingke4981 2018-09-30 17:30
浏览 34
已采纳

如何将一行的AVERAGE放到新列中?

Hey everyone I am using golang to build a super simple API. I have this json data being passed from a POST request and being stored in my DB. I would like to take the tts data which is an integer array and average that array and place it in the ttc column and return that number on the json response. I am having a hard time doing that any help would be greatly appreciated. My source code is below as well as my DB Model. I know I would have to use the AVG() function somehow in postgres but I am brand new to postgres so I am super confused.

main.go

package main

import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/lib/pq"
"github.com/rs/cors"
"log"
"net/http"

_ "github.com/jinzhu/gorm/dialects/postgres"
)

type Resource struct {
    gorm.Model

    Name        string
    TTS     pq.Int64Array `gorm:"type:integer[]"`
    TTC int
}

var db *gorm.DB
var err error

func main() {
    router := mux.NewRouter()

    db, err = gorm.Open(
        "postgres",
        "host=localhost"+" user=postgres"+
        " dbname=Shoes"+" sslmode=disable password=root")

    if err != nil {
        panic("failed to connect database")
    }

    defer db.Close()

    db.AutoMigrate(&Resource{})

    router.HandleFunc("/resources", GetResources).Methods("GET")
    router.HandleFunc("/resources/{id}", GetResource).Methods("GET")
    router.HandleFunc("/resources", CreateResource).Methods("POST")
    router.HandleFunc("/resources/{id}", DeleteResource).Methods("DELETE")

    handler := cors.Default().Handler(router)

    log.Fatal(http.ListenAndServe(":8080", handler))
}

func GetResources(w http.ResponseWriter, r *http.Request) {
    var resources []Resource
    db.Find(&resources)
    json.NewEncoder(w).Encode(&resources)
}

func GetResource(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    var resource Resource
    db.First(&resource, params["id"])
    json.NewEncoder(w).Encode(&resource)
}

func CreateResource(w http.ResponseWriter, r *http.Request) {
    var resource Resource
    json.NewDecoder(r.Body).Decode(&resource)
    db.Create(&resource)
    json.NewEncoder(w).Encode(&resource)
}

func DeleteResource(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    var resource Resource
    db.First(&resource, params["id"])
    db.Delete(&resource)

    var resources []Resource
    db.Find(&resources)
    json.NewEncoder(w).Encode(&resources)
}

I am thinking I could do something like

db.Select("AVG(tts)")

I am just not sure how to put that result in the column ttc

  • 写回答

1条回答 默认 最新

  • dongzhuanlei0768 2018-09-30 19:36
    关注

    Since the json of the post request already contains the tts_data, you can get the average before setting it in the database

    sum := 0
    for _, i := range tts_data {
     sum += i
    }
    avg := sum / len(tts_data)
    // save the data in your db
    rs := Ressource{Name: "name", TTS: tts_data, ttc: avg}
    b := db.Create(&rs)
    if b {
      // send all the resource
      json.NewEncoder(w).Encode(&rs)
      // or send only the avg
      json.NewEncoder(w).Encode(struct{avg: int}{avg: avg})
    } else {
      // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000