简体   繁体   中英

Concatenate multiple rows in one fields

I have 2 tables as following

Table1
Id       TagNo        FBay      FPanel      TBay     TPanel
------------------------------------------------------------
 1        10000        A1         A2         E4        F2
 2        10001        A2         R2         F2        Q1


Table2
 Id      TagNo    CNo     FDevice
-----------------------------
  1       10000    1       X101
  2       10000    2       XF09
  3       10000    3       X101
  4       10000    4       XY
  5       10001    1       X20
  6       10002    2       X20
  7       10003    3       X20

I want to have this result

  TagNo        FBay      FPanel      TBay     TPanel       FDevice
  -----------------------------------------------------------------
   10000        A1         A2         E4        F2       X101,XF09,XY
   10001        A2         R2         F2        Q1       X20

The numbers of records are too much so if I want to use Stuff Tsql it takes arounf 7 minutes to have a result back from database which is not so good. so is there any solution to have this result?

this is the part of the query which i used stuff in it

SELECT Distinct TagNo, FDevice = STUFF((SELECT ',' + FDevice FROM Table2 i
                      WHERE
                      i.TagNo = o.TagNo AND
                      FOR XML PATH('')),1,1,'')
                      FROM Table2 o
                      GROUP BY TagNo

There is no any kind of Stuff() function in LINQ. But may be you can achieve the same using this

var results = from rw in Table2
            group rw.FDevice by new { rw.TagNo } into grp
            select new { grp.Key.TagNo, FDevice = string.Join (", ", grp) };

Note: I have not tested it into VS, so there might be any syntax error. Please comment if any, Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM