表A:tb_product
id 自增长
productid 产品id (唯一)表B:tb:tb_type
id 自增长
typename 类名
flag 类标记 表C:tb_product_type
id 自增长
typeid
appid
现有数据:
tb_product:
1 产品1
2 产品2
3 产品3tb_type:(flag只有1或者2标记)
1 类别1 1
2 类别2 1
3 类别3 2
4 类别4 2
5 类别5 1tb_product_type:
1 1 1
2 1 3
3 2 2
4 2 3
5 3 5
6 3 4每个产品分别对应一个flag=1的类和一个flag=2的类
即:tb_product_type表中每个产品id都会有2条记录现在想生成这样的表产品id type1id type1name type2id typename
1 1 类别1 3 类别3
2 2 类别2 3 类别3
3 5 类别5 4 类别4type1 为flag=1的类id
type1name 为flag=1的类名
求高手

解决方案 »

  1.   

    select appid,
    type1id = (select typeid from tb_product_type where flag =1 and id = t.id),
    type1name = (select typename from tb_product_type,tb_type where flag =1 and
    tb_product_type.typeid = tb_type.id and tb_product_type.id = t.id),
    type2id = (select typeid from tb_product_type where flag =2 and id = t.id),
    type2name = (select typename from tb_product_type,tb_type where flag =2 and
    tb_product_type.typeid = tb_type.id and tb_product_type.id = t.id) from tb_product_type t
      

  2.   

    --> 测试数据:#a
    if object_id('tempdb.dbo.#a') is not null drop table #a
    create table #a(id int, productid varchar(8))
    insert into #a
    select 1, '产品1' union all
    select 2, '产品2' union all
    select 3, '产品3'
    --> 测试数据:#b
    if object_id('tempdb.dbo.#b') is not null drop table #b
    create table #b(id int, typename varchar(8), flag int)
    insert into #b
    select 1, '类别1', 1 union all
    select 2, '类别2', 1 union all
    select 3, '类别3', 2 union all
    select 4, '类别4', 2 union all
    select 5, '类别5', 1
    --> 测试数据:#c
    if object_id('tempdb.dbo.#c') is not null drop table #c
    create table #c(id int, appid int, typeid int)
    insert into #c
    select 1, 1, 1 union all
    select 2, 1, 3 union all
    select 3, 2, 2 union all
    select 4, 2, 3 union all
    select 5, 3, 5 union all
    select 6, 3, 4select c1.appid productid,
    b1.id type1id, b1.typename type1name,
    b2.id type2id, b2.typename type2name
    from #c c1
    join #b b1 on c1.typeid=b1.id and b1.flag=1
    join #c c2 on c1.appid=c2.appid
    join #b b2 on c2.typeid=b2.id and b2.flag=2/*
    productid   type1id     type1name type2id     type2name
    ----------- ----------- --------- ----------- ---------
    1           1           类别1       3           类别3
    2           2           类别2       3           类别3
    3           5           类别5       4           类别4
    */