简体   繁体   English

Groovy groupby或映射SQL

[英]Groovy groupby or map for a sql

I have written the following query 我写了以下查询

def result=GuruActivity.executeQuery("select P.id, P.postBy, P.totalUp from GuruActivity as P where P.totalUp>5")
println result
render "done"

I am getting result like 我得到像

[1, AAA, 7], [2, AAA, 10], [3, AAA, 7], [7, BBB, 7], [9, CCC, 7]

Now how do get the P.ID in the following format (in a map) here i am getting the id that are over 5 totalUp 现在如何获取以下格式的P.ID(在地图中),这里我得到的ID超过5 totalUp

AAA : [1,2,3]
BBB : [7]
CCC : [9]

How do i do this? 我该怎么做呢?

One way is to use collection's groupBy . 一种方法是使用collection的groupBy

def list = [[1, 'AAA', 7], [2, 'AAA', 10], 
           [3, 'AAA', 7], [7, 'BBB', 7], [9, 'CCC', 7]]

assert list.groupBy{it[1]}
           .collectEntries{k, v-> [k, v.collect{it[0]}]} == 
                          ['AAA':[1, 2, 3], 'BBB':[7], 'CCC':[9]]​​​​​​

Another would be inject 另一个将被注入

list.inject( [:].withDefault { [] } ) { m, e ->
    m[ e[ 1 ] ] << e[ 0 ]
    m
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM