选择行的所有字段并根据一列对它们进行分组

时间:2017-05-29 04:33:23

标签: java sql oracle hibernate

数据库中的表有列a,b,c。数据库中的每两行在列c中具有相同的值。我想获取并存储这些对以用于下一个操作。 我正在使用hibernate(但不是标准接口)。 什么是最好的解决方案?

人员实体:

+--------------+----+-------+---+
| person Object| a  |b      | c |
+--------------+----+-------+---+
|     p1       |  w | d     |  1 |
|     p2       |  d | d     |  2 |
|     p3       |  f | e     |  3 |
|     p4       |  x | f     |  1 |
|     p5       |  w | g     |  2 |
|     p6       |  g | s     |  3 |
|     p7       |  x | h     |null|
|     p8       |  q | null  |  4 |
|     p9       |  w | null  |null|

预期产量: 具有相同“C”的行对列表:[{p1,p4},{p2,p5},{p3,p6}]

p1从实体检索hibernate对象而不是字符串或列。 p1是第一行的对象。我想获得一对hibernate对象,一对行。

1 个答案:

答案 0 :(得分:0)

 with data (rn, person, a, b, c) as
 (
   select rownum rn, t.* from 
   (
    select     'p1',         'w' , 'd'     ,  1 from dual union all 
    select     'p2',         'd' , 'd'     ,  2 from dual union all 
    select     'p3',         'f' , 'e'     ,  3 from dual union all 
    select     'p4',         'x' , 'f'     ,  1 from dual union all 
    select     'p5',         'w' , 'g'     ,  2 from dual union all 
    select     'p6',         'g' , 's'     ,  3 from dual union all 
    select     'p7',         'x' , 'h'     ,  null from dual union all
    select     'p8',         'q' , null    ,  4 from dual union all 
    select     'p9',         'w' , null    ,  null from dual
   ) t
)
,
cte (rn, person, a, b, c, pair) as
(
  select rn, person, a, b, c, null from data
  union all
  select data.rn, null, null, null, null,  '{' ||  cte.person || ',' || data.person || '}' from cte join data on (cte.c = data.c and cte.rn < data.rn)
)
select 
  '"C":' || 
  '[' || listagg(pair, ',')  within group(order by rn) || ']' result 
from cte 
where pair is not null;