我有一张表table1,结构如下:
column1 column2
a a1
a a2
a a3
b b1
b b2
我想通过一条SQL语句实现下列结果:
col1 col2 col3
a a1,a2,a3 3
b b1,b2 2
我用Select column1 col1,count(*) col3 from table1 group by column1已经选出了两列col1和col3,可是不知怎么把col2选出来?
请问高手,如何将字段column2中的值拼接起来?
很久以前我回答过这样的问题。字符串不可能和数字一样处理,因为数字统计(无论是count还是sum或者avg)都是不需要考虑排序的,而字符串就完全不一样,所以数据库不可能提供类似的操作。
这个问题的解决方法可以用一个function来处理:create or replace function get_conc_col2(p_col1 varchar2) return varchar2
as
w_ret varchar2(1000);
begin
for i in (select col2 from table1 where col1=p_col1) loop
w_ret := w_ret||','||i.col2;
end loop;
return w_ret;
end get_conc_col2;
/
select col1,get_conc_col2(col1) col2,cnt from
(select col1,count(*) cnt from table1 group by col1);