在Grid中连续查看重复记录

时间:2017-04-05 06:48:26

标签: asp.net sql-server c#-4.0

此查询返回多个记录,我在网格中显示结果 我希望在具有多列的记录中显示所有记录

select  Acceptor.Terminal, Acceptor.AcceptorName 
            ,Em.CauseDamage, Em.DescriptionDamage                                        
            from Em  
            left outer join Acceptor on Acceptor.Terminal = Em.Terminal 
            where     (Acceptor.Terminal = '70460440')



Terminal  AcceptorName CauseDamage   DescriptionDamage
-------------------------------------------------------
70460440  Alvin        reason1       Comments1
70460440  Alvin        reason2       Comments2
70460440  Alvin        reason3       Comments3

我希望在网格中显示结果

Terminal  AcceptorName  CauseDamage1   DescriptionDamage1 CauseDamage2  DescriptionDamage2  CauseDamage3   DescriptionDamage3
--------------------------------------------------------------------------------------------------------------------
70460440  Alvin         reason1       Comments1           reason2       Comments2           reason3        Comments3   

1 个答案:

答案 0 :(得分:0)

此查询只是让您开始工作,并指导您获得最终结果。 这不是最终结果查询所以你可以试试这个,它会指导你在你的情况下使用PIVOT,它是用于修复的动态列。所以你可以根据你的要求修改它;

select * from Tempt
go
select * from  tempt2
go
DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumnname AS NVARCHAR(MAX)
DECLARE   @PivotColumns_cd AS NVARCHAR(MAX)
--Get unique values of pivot column  
SELECT   @PivotColumnname= COALESCE(@PivotColumnname + ',','') +
QUOTENAME(name)
FROM (select name from Tempt where towncd = '0001') AS PivotExample
SELECT   @PivotColumns_cd = COALESCE(@PivotColumns_cd + ',','') + 
QUOTENAME(second_col)
FROM (select second_col from Tempt where towncd = '0001') AS PivotExample_a
--Create the dynamic query with all the values for
--pivot column at runtime
print(@PivotColumnname)
print(@PivotColumns_cd)
SET   @SQLQuery =
 '( SELECT name2,towncd,' +   @PivotColumnname + ',' +   @PivotColumns_cd +'
   FROM (select  tempt2.name2, tempt2.towncd ,Tempt.name, Tempt.second_col
    from Tempt  left outer join tempt2 on tempt2.towncd = Tempt.towncd 
    where tempt2.towncd = ''0001'')x
    PIVOT( max(name) FOR name IN (' + @PivotColumnname+')) 
    AS p1
    PIVOT( max(second_col) FOR second_col IN (' + @PivotColumns_cd+')) AS 
P)'execute(@SQLQuery)

这里我创建了两个表以匹配您的场景并将测试数据放入其中。 诱惑:

seqno   name    towncd  Counttown_cd    second_col
---------------------------------------------------
1       usman   0001    1               dam1
3       test    0003    NULL            NULL
1       usman2  0001    2               dam2
2       usman3  0001    3               dam3

tempt2:

 id towncd  name2
------------------
1   0001    man
2   0003    test

此查询将如下所示:

 name2  towncd  usman   usman2  usman3  dam1    dam2    dam3
-------------------------------------------------------------
man     0001    NULL    NULL    usman3  NULL    NULL    dam3
man     0001    NULL    usman2  NULL    NULL    dam2    NULL
man     0001    usman   NULL    NULL    dam1    NULL    NULL