表1公司id  公司名称
1       公司1
2       公司2
表2公司id  产品
1       产品11
1       产品12
2       产品21
想要查出的结果是 
公司id 公司名称 产品1   产品2
1      公司1     产品11  产品12
2      公司2     产品21  得咋写呢。
大家帮帮我 谢谢 先咯

解决方案 »

  1.   

    select 表1.公司id,公司名称,产品1,产品2 from 表1,表2 where 表1.公司id=表2.公司id
      

  2.   

    select 表1.公司id,公司名称,产品1,产品2 from 表1,表2 where 表1.公司id=表2.公司id这个是不对的应该 不能达到效果的。
      

  3.   

    很明显select 表1.公司id,公司名称,产品1,产品2 from 表1,表2 where 表1.公司id=表2.公司id是完全错误的!
      

  4.   


    create table #c( id int,name1 varchar(10))
    insert #c
    select 1,       '公司1'union all
    select 2,       '公司2'
    create table  #a(id int, name varchar(10)) 
    insert #a
    select 1,       '产品11' union all
    select 1,       '产品12' union all
    select 2,       '产品21'
    select *,num=identity(int,1,1),count=1 into #b from #a
    update b set count=(select count(1)from #b where id=b.id and num!>b.num) from #b bdeclare @a varchar(1000)
    set @a='select c.* '
    select @a=@a+',[产品'+convert(varchar,count)+']= max(case count when '+convert(varchar,count)+' then name else '''' end)'
    from (select distinct count from #b)a
    set @a=@a+' from #c c left join #b b on c.id=b.id group by c.id, name1'
    exec(@a)
    --drop table #a 
    --drop table #b 
    --drop table #c
    结果为:
    id          name1      产品1        产品2        
    ----------- ---------- ---------- ---------- 
    1           公司1        产品11       产品12
    2           公司2        产品21
      

  5.   

    谢谢大家。roy_88(学习的激情)  尤其感谢。
    你给的代码是可行的,但是我还有个问题能帮我解答一下吗
    就是如果有三个产品,四个产品,那怎么办呢