SQL:将列的值合并为一行

时间:2018-10-11 08:33:30

标签: sql sql-server

Microsoft SQL Server 2014

这是我的发言

SELECT dbo.Request.RequestId, dbo.Employee.Givenname, dbo.Employee.Surname, Employee_1.Surname AS Expr1, Employee_1.Givenname AS Expr2
  FROM dbo.Request 
       INNER JOIN
          dbo.Employee ON dbo.Request.StartedBy_EmployeeId = dbo.Employee.EmployeeId 
       INNER JOIN
           dbo.Employee AS Employee_1 ON dbo.Request.TargetEmployeeId = Employee_1.EmployeeId
  WHERE (dbo.Request.State = '4')

但是我不需要将命令的输出分成不同的列。 因此,而不是此输出:

|2981  |  Tom   |   Johnsen   |   random    |   name |

我想要此输出:

|2981- Tom Johnsen - random name|

2 个答案:

答案 0 :(得分:1)

使用concat函数

SELECT concat(dbo.Request.RequestId,'- ', dbo.Employee.Givenname, '',dbo.Employee.Surname,'- ', Employee_1.Surname,'', Employee_1.Givenname )
FROM            dbo.Request INNER JOIN
                         dbo.Employee ON dbo.Request.StartedBy_EmployeeId = dbo.Employee.EmployeeId INNER JOIN
                         dbo.Employee AS Employee_1 ON dbo.Request.TargetEmployeeId = Employee_1.EmployeeId
WHERE        (dbo.Request.State = '4')

答案 1 :(得分:0)

SELECT  dbo.Request.RequestId +'|'+ dbo.Employee.Givenname+'|'+ dbo.Employee.Surname ...etc. FROM
    …

但是通常您会选择列并在客户端中进行格式化