日期:2014-05-17  浏览次数:20902 次

请教一个效率较高的sql语句
现有如果情况的数据 一张表有下列数据
X Y 
1 11
1 12
1 13
2 2
3 31
3 32
4 4

我想查询时查询结果是  
1 11,12,13(将这三个数据合并为一个结果字段)
2 2
3 31,32
4 4  
注:表中数据可能上千万,但一般同一X对应Y的值不会超过100个 求大侠指教啊,效率最好高点啊

------解决方案--------------------
SQL code

select X,wm_concat(Y) from 你的表 group by X;

------解决方案--------------------
用wm_concat函数就能很容易满足你的要求,当然这个函数是10g之后才有的。你的oracle版本应该是10g之后的吧?

SQL code
select x, wm_concat(y) from t group by x;

------解决方案--------------------
select X,wm_concat(Y) from 你的表 group by X;

------解决方案--------------------
SQL code
with t(x, y, z) as (  
          select 1, 11, 'B' from dual
union all select 1, 12, 'A' from dual
union all select 1, 13, 'C' from dual
union all select 2, 2, 'G' from dual
union all select 3, 31, 'D' from dual
union all select 3, 32, 'F' from dual
union all select 4, 4, 'M' from dual
)
select x, y from (
  select x,
    wm_concat(y) over (partition by x order by z) y,
    row_number() over (partition by x order by z desc) rn
  from t) where rn = 1;

------解决方案--------------------
探讨
引用:

用wm_concat函数就能很容易满足你的要求,当然这个函数是10g之后才有的。你的oracle版本应该是10g之后的吧?

SQL code
select x, wm_concat(y) from t group by x;
关键问题我忘说了 我还想对Y结果字段按Z字段进行排序

------解决方案--------------------
SQL code

with t as (  
          select 1 as x, 11 as y, 'B' as z from dual
union all select 1, 12, 'A' from dual
union all select 1, 13, 'C' from dual
union all select 2, 2, 'G' from dual
union all select 3, 31, 'V' from dual
union all select 3, 32, 'F' from dual
union all select 4, 4, 'M' from dual
)
select X,wm_concat(Y)
from ( select * from t order by Z)
group by X;