2

我在 oracle 中有一张桌子,my_table比如

userid            card_no
-------           -------
 111                 A1
 111                 A5
 112                 A3
 113                 A4
 111                 A6
 112                 A8
 113                 A9

在我的 JSP 页面中,我想显示:

------------------------
user_id   card numbers
-------   --------------
111       A1,A5,A6.
112       A3,A8
113       A4,A9
------------------------

GROUP BY没有给出结果。

4

3 回答 3

1

从 Oracle 10g 开始,您可以通过 usingmodel子句达到预期的效果:

SQL> with t1(userid, card_no) as(
  2   select 111,'A1' from dual union all
  3   select 111,'A5' from dual union all
  4   select 112,'A3' from dual union all
  5   select 113,'A4' from dual union all
  6   select 111,'A6' from dual union all
  7   select 112,'A8' from dual union all
  8   select 113,'A9' from dual
  9  )
 10  select userid
 11       , card_no
 12    from ( select userid
 13                , rtrim(res, ',') as card_no
 14                , rn
 15             from t1
 16            model
 17            partition by (userid)
 18            dimension by (row_number() over(partition by userid 
 19                                            order by card_no) as rn)
 20            measures(card_no, cast(null as varchar2(255)) as res)
 21            rules(
 22               res[any] order by rn desc = card_no[cv()] || ',' || res[cv() + 1]
 23            )
 24         ) s
 25  where s.rn = 1
 26  order by userid
 27  ;

结果:

 USERID  CARD_NO
 ----------------
 111     A1,A5,A6
 112     A3,A8 
 113     A4,A9

SQLFiddle 演示

了解有关示范条款的更多信息

此外,还有很多其他的字符串聚合技术。

于 2013-08-27T14:47:46.477 回答
0

您可以使用从LISTAGGOracle 11g R2 开始的功能。

例如

SELECT deptno
, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM   emp
GROUP  BY
deptno;
于 2013-08-27T14:25:31.177 回答
0
select userid, wm_concat(card_no) from table_name group by userid
于 2013-08-27T14:28:01.367 回答