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

如何取出按 B 列分组后 A 列相同的数据?
本帖最后由 happyhhb 于 2013-04-23 22:50:54 编辑
不知道问题表述是否正确
假设有表 t 如下:
A列  B列
b    2
c    2
a    3
b    1
e    3
b    3
c    1
d    2
a    1

执行 “select * from t group by B列”  后结果如下 

A列  B列
a    1
b    1
c    1
b    2
d    2
c    2
a    3
e    3
b    3

这样结果就按 B列 分为3组了,其中1、2、3三个组 A列 都出现过 b
那么我如何对原始表 t 写一个语句一次性就得到三个组都会重复出现的 b 这个结果呢:
A列  B列
b    1,2,3

请不要类似这样 
select * from (select * from t where B = '1') a,(select * from t where B = '2') b, (select * from t where B = '3') c where a.A = b.A and b.A = c.A

因为实际操作中B的内容和数量是不可确定的

不知道如何写这个语句呢,请各位大虾指教,谢谢 ^_^

抱歉,就剩25分了,呵呵,谢谢

------解决方案--------------------
哥们,你的问题描述的确实有点问题...如果你曾经实际执行过
 “select * from t group by B列”  的话,他会告诉你非分组函数
如果你期望是如下这个样子:
A列  B列
b    1,2,3

可以参考一个Oracle一直没有公布的函数 WMSYS.WM_CONCAT()

SELECT A,WMSYS.WM_CONCAT(B)
FROM 你的表
GROUP BY A;


------解决方案--------------------
楼上用了WM_CONCAT,我写个listagg的。。

select a, listagg(b, ',') within GROUP(order by b) 
from t 
group by a
------解决方案--------------------
create table tab
(A varchar(50),B int)
insert into tab
select 'b',    '2' union all
select 'c',    '2' union all
select 'a',    '3' union all
select 'b',    '1' union all
select 'e',    '3' union all
select 'b',    '3' union all
select 'c',    '1' union all
select 'd',    '2' union all
select 'a',    '1' 


select distinct A,STUFF((
select ','+convert(varchar,B) from (
select * from tab where A='b' 
)b order by B for xml path('')),1,1,'')as B from tab where A='b'
union all
select a,convert(varchar,B) from tab where A not in('b') order by B

A   &nb