现有如下表格
Table:rsi_attributes 主表
attributeCode attributeName
1            name
2            description
3            brand
4            upc
5            itemNumber
6            storeNumber
7            itemDescription Table: rsi_masterdata 从表
reference attributeCode attributeValue
1                1 GTIN 1
1                2 Global Trade Item Number1
1                3 HP laptop
1                4 4002533276811 
1                5 12564439
2                1 GTIN 2
2                2 Global Trade Item Number2
2                3 HP Printer
2                4 4002533276812 
主表与从表之间通过attributeCode相互关联
先要求查询结果如下:
reference name        description        brand       upc         itemnumber
1         GTIN 1   Global Trade Item Number1 HP       4002533276811  12564439
2         GTIN 2   Global Trade Item Number2  HP Printer       4002533276812 
请各位高数,帮忙一起解决一下,由于小弟可用积分较少,只能意思一下

解决方案 »

  1.   

    declare @columnName varchar(2000)
    declare @isnullName varchar(2000)select @columnName = isnull(@columnName+',','')  +'['+ attributeName + ']',
    @isnullName = isnull(@isnullName+',','') + 'isnull(' + attributeName + ','''') as '+attributeName+''
    from dbo.rsi_attributes
    where attributecode in (select attributecode from dbo.rsi_masterdata)declare @sql nvarchar(1000)
    set @sql = 'select reference,' + @isnullname + 
    ' from 
    (
    select b.reference,a.attributename ,b.attributevalue
    from dbo.rsi_attributes a , dbo.rsi_masterdata b 
    where a.attributecode = b.attributecode ) a 
    pivot (max(attributevalue) for attributename in (' + @columnname + ')) as pvt'exec sp_executesql @sql