TSQL将多行组合成一行

buz*_*jay 0 t-sql sql-server-2008

我正在尝试创建一个查询来组合以下信息:

FileID  ErrorCode  ErrorDesc             ErrorCount
  1         4      Bad File Name             3
  2         6      Bad File Code            56
  3         4      Bad File Name             2
  3        12      Line Length Invalid       3
  3        17      Missing Req Fields      150
Run Code Online (Sandbox Code Playgroud)

我想基于所有行组合,FileID以便给定的所有信息FileID将出现在与以下相同的行上:

1  4  Bad File Name     3
2  6  Bad File Code    56
3  4  Bad File Name     2     12  Line Length Invalid  3     17 Missing Req Fields  150
Run Code Online (Sandbox Code Playgroud)

我运行它的问题将是每个给定文件的未知数量的错误.它可能有1-50个错误,我想将所有这些信息组合在一行中.我不确定这是否可行,或者是否有其他方法可以查看此问题.我的最终目标是最终根据这些数据创建报告.谢谢!

Mik*_*son 5

declare @T table (FileID int, ErrorCode int, ErrorDesc varchar(max), ErrorCount int)

insert into @T values
(1,             4,                    'Bad File Name',          3),
(2,             6,                    'Bad File Code',          56),
(3,             4,                    'Bad File Name',          2),
(3,             12,                   'Line Length Invalid',    3),
(3,             17,                   'Missing Req Fields',     150)

select FileID,
       (select cast(ErrorCode as varchar(10))+' '+ErrorDesc+' '+cast(ErrorCount as varchar(10))+' '
        from @T as T2
        where T1.FileID = T2.FileID
        for xml path(''), type).value('.', 'varchar(max)') 
from @T as T1
group by FileID
Run Code Online (Sandbox Code Playgroud)