根据同一个表上不同的列值选择其他列的多个值

时间:2013-08-27 14:24:33

标签: sql oracle jsp

我在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没有给出结果。

3 个答案:

答案 0 :(得分:1)

从Oracle 10g开始,您可以使用model子句获得所需的结果:

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 Demo

Find out more关于模型子句

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

答案 1 :(得分:0)

您可以使用Oracle 11g R2中的LISTAGG功能。

e.g。

SELECT deptno
, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM   emp
GROUP  BY
deptno;

答案 2 :(得分:0)

select userid, wm_concat(card_no) from table_name group by userid