【问题标题】:select all fields of rows and group them based on one column选择行的所有字段并根据一列对它们进行分组
【发布时间】:2017-10-29 07:11:12
【问题描述】:

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

个人实体:

+--------------+----+-------+---+
| 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 是从实体而不是字符串或列中检索到的休眠对象。 p1 是第一行的对象。我想得到一对休眠对象,一对行。

【问题讨论】:

  • 你的问题不清楚,举个例子,数据和需要什么输出。
  • @Ramki 我编辑了我的帖子。谢谢
  • 你可以试试 LISTAGG () 这将给出多个行值 int 单列搜索互联网中的一些示例techonthenet.com/oracle/functions/listagg.php
  • @Ramki p1 是从实体中检索的休眠对象,而不是字符串或列。 p1 是第一行的对象。我想得到一对休眠对象,一对行。

标签: java sql oracle hibernate


【解决方案1】:
 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;

【讨论】:

  • 对不起..我认为我的输入不清楚...我假设 p1 是从实体而不是字符串和列中检索到的休眠对象。 p1 是第一行的对象
猜你喜欢
  • 2013-07-27
  • 2019-01-14
  • 2019-09-28
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多