tableA  id为主键
id name
1 name1
2 name2
3 name3
4 name4tableB id为外键,A_id和tea_id构成联合主键
A_id tea_id tea_name
1 1 无名1
1 2 无名22
2 1 无名3
2 2 无名41
2 3 无名5
3 1 无名6
4 1 无名7
4 2 无名8
要求查询结果为:
id name tea_name_1 tea_name_2 tea_name_3
1 name1 无名1         无名22
2 name2 无名3         无名41         无名5
3 name3 无名6
4 name4 无名7         无名8
tableA和tableB是一个1:n的关系
也就是根据tableA中的id,查询出tableB中与之对应的多条数据,并横向列出。tableB中的tea_id为集合{1,2,3}中一值。和id构成的唯一主键中,tea_id的排序为由小到大。要求:不用select A_id,tea_name 
         form tableB 
         where A_id in( select id from tableA group by id) and tea_id='1'
.....类似的分步查询,然后拼凑结果的方法解决。(因为这里的tea_id,我不希望是定死的,谢谢!!!)
谢谢!!!我不知道我的问题是否描述清楚,还望各位海涵!!!

解决方案 »

  1.   

    select a.id , a.name , 
      max(case b.tea_id when 1 then b.tea_name else '' end) 'tea_name1',
      max(case b.tea_id when 2 then b.tea_name else '' end) 'tea_name2',
      max(case b.tea_id when 3 then b.tea_name else '' end) 'tea_name3'
    from tablea a , tableb b
    where a.id = b.a_id
    group by a.id , a.name
    order by a.id
      

  2.   

    --参阅此例:
    有表TableA:   
    col1         col2         col3 
    A               x                   1 
    A               y                   2 
    A               z                   3 
    B               x                   2 
    B               y                   1 
    B               z                   1 是否可以把数据显示成(用一个SQL): 
                    x         y       z 
    A             1         2       3 
    B             2         1       1 如果col1,col2的值是变化,显示列是否动态变化? 
    -----------
    SQL> with a as (select 'a' con1,'x' col2,1 col3 from dual
      2             union all
      3             select 'a' con1,'y' col2,2 col3 from dual
      4             union all
      5             select 'a' con1,'z' col2,3 col3 from dual
      6             union all
      7             select 'b' con1,'x' col2,2 col3 from dual
      8             union all
      9             select 'b' con1,'y' col2,1 col3 from dual
     10             union all
     11             select 'b' con1,'z' col2,1 col3 from dual
     12             )
     13  select con1,max(decode(rn,1,col3,null)) x,
     14              max(decode(rn,2,col3,null)) y,
     15              max(decode(rn,3,col3,null)) z
     16  from (select a.*,row_number()over(partition by con1 order by col2) rn from a)
     17  group by con1
     18  /
     
    CON1          X          Y          Z
    ---- ---------- ---------- ----------
    a             1          2          3
    b             2          1          1