【问题标题】:Dynamically Bind gridview DataField动态绑定gridview DataField
【发布时间】:2015-01-05 09:56:11
【问题描述】:

我有两张桌子

table1

productName         category     S_Id    value

p1                 cat1           1        year
p1                 cat1           2        test1
p1                 cat1           3        test2


table2

S_Id                  specificatio

1                         year
2                         test1
3                         test2

而我的需要是像这样绑定网格视图

productName        category    year      test1    test2

p1                    cat1      1          2        3

我试过了

select P.productName,P.category,S.specification from table1 P inner join table2 S on(P.S_Id=S.S_Id)

但它显示的结果喜欢

 productName        category        specification

    p1                    cat1       year
    p1                    cat1       test1
    p1                    cat1       test2

任何人都可以帮助如何实现这一点。在此先感谢

【问题讨论】:

  • 您需要对数据进行透视。

标签: c# sql sql-server sql-server-2008


【解决方案1】:

试试这个:

create table table1
(
productname varchar(10),
category varchar(10),
S_Id int,
value varchar(10)
);

insert into table1 values('p1','cat1',1,'year');
insert into table1 values('p1','cat1',2,'test1');
insert into table1 values('p1','cat1',3,'test2');

create table table2
(
S_Id int,
specification varchar(10)
);

insert into table2 values(1,'year');
insert into table2 values(2,'test1');
insert into table2 values(3,'test2');

/动态查询预期结果/

Declare @cols varchar(max);
Declare @sql varchar(max);

select @cols = STUFF((SELECT  ',' + QUOTENAME(specification)
                from table2
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'');

 SET @SQL = N'select productName,category,'+@cols+'
    from
    (
    select t1.productname,t1.category,t2.S_ID,t2.Specification
    from table1 t1
    inner join 
    table2 t2
    on t1.S_ID = t2.S_ID
    )x
    pivot
    (
        MAX(S_Id) 
        FOR SPECIFICATION IN ('+@cols+')
    ) PV';
EXEC(@SQL);     

结果

productName   category  year  test1  test2
------------------------------------------
p1              cat1     1      2      3

【讨论】:

    【解决方案2】:

    试试这个,

    SELECT * FROM (SELECT     P.productName,
               P.category,
               S.specification,P.S_Id
    FROM       #table1 P
    INNER JOIN #table2 S ON( P.S_Id = S.S_Id ) )A
    PIVOT (MAX(A.S_Id) FOR A.SPECIFICATION IN ([year],[test1],[test2])) PV
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多