如何在SQL中分隔行数据逗号?

时间:2010-12-07 18:33:13

标签: sql-server function stored-procedures

我有一个查询会在输出后返回。

(结果不是所有时间都不相同,意味着它有时会给出3个类别,有时候会有8个类别等。)

CategoryName

  Test1
  Test2
  Test3

现在我希望商店程序以逗号分隔格式返回这些日期。 例如输出字符串应该类似于:Test1,Test2,Test3

请告诉我如何实现这一目标?

5 个答案:

答案 0 :(得分:5)

这适用于数据中的所有字符:

set nocount on;
declare @YourTable table (BirthDay datetime, PersonName varchar(20))
insert into @YourTable VALUES ('1-10-2010',     'Joe'  )
insert into @YourTable VALUES ('2-10-2010',     'Bob  <&>'  )
insert into @YourTable VALUES ('2-10-2010',     'Alice')
set nocount off


--Concatenation with FOR XML and eleminating control/encoded character expansion "& < >"
SELECT
    p1.BirthDay
        ,STUFF(
                   (SELECT
                        ', ' + p2.PersonName
                        FROM @YourTable p2
                        WHERE p2.BirthDay=p1.BirthDay
                        ORDER BY p2.PersonName
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS PersonNames
    FROM @YourTable p1
    GROUP BY p1.BirthDay

输出:

BirthDay                PersonNames
----------------------- ------------------------
2010-01-10 00:00:00.000 Joe
2010-02-10 00:00:00.000 Alice, Bob  <&>

(2 row(s) affected)

答案 1 :(得分:2)

尝试COALESCEISNULL

DECLARE @returnValue varchar(MAX)

SELECT
  @returnValue = COALESCE(@returnValue + ', ', '') + CategoryName
FROM
  TableName

答案 2 :(得分:0)

查看类似(完整工作示例

的内容
DECLARE @Table TABLE(
        ID INT,
        Val VARCHAR(50)
)
INSERT INTO @Table (ID,Val) SELECT 1, 'A'
INSERT INTO @Table (ID,Val) SELECT 1, 'B'
INSERT INTO @Table (ID,Val) SELECT 1, 'C'
INSERT INTO @Table (ID,Val) SELECT 2, 'B'
INSERT INTO @Table (ID,Val) SELECT 2, 'C'

--Concat
SELECT  t.ID,
        STUFF((
                SELECT  ',' + t1.Val 
                FROM    @Table AS t1 
                WHERE   t1.ID = t.ID 
                FOR XML PATH('')
                ), 1, 1, '')
FROM    @Table t
GROUP BY t.ID

另外,您可能会发现谷歌搜索会提供很多答案。

答案 3 :(得分:0)

一个意思是:

SELECT STUFF((
  SELECT ',' + CategoryName AS [text()]
  FROM YourTable
  FOR XML PATH('')
), 1, 1, '')

...但要注意将被转义的XML实体 - 例如& => &amp;

答案 4 :(得分:0)

只需在商店程序中修改KM答案

ALTER Procedure [dbo].[Payroll_rptAbsentReport]
@FromDate DateTime,
@ToDate DateTime,
@GFacatoryID UniqueIdentifier
As
Begin
-- Temporary table for Row data seperation
CREATE TABLE TestTable(GEmployeeGenInfoID uniqueidentifier, dtAttendDateTime varchar(max))
INSERT INTO 
            TestTable(GEmployeeGenInfoID, dtAttendDateTime)
      SELECT 
             Payroll_tblAttendance.GEmployeeGenInfoID
            ,CONVERT(VARCHAR(max), dtAttendDateTime, 105)dtAttendDateTime
      FROM  Payroll_tblAttendance
            INNER JOIN PIS.dbo.PIS_tblEmployeeGenInfo as EmployeeGenInfo ON Payroll_tblAttendance.GEmployeeGenInfoID= EmployeeGenInfo.GEmployeeGenInfoID
            WHERE Payroll_tblAttendance.DayStatusID = 0  AND EmployeeGenInfo.GFactoryID=@GFacatoryID AND Payroll_tblAttendance.dtAttendDateTime Between @FromDate and @ToDate ORDER BY dtAttendDateTime
-- Final expected output
SELECT DISTINCT
      EmployeeGenInfo.StrEmpName
     ,EmployeeGenInfo.StrEmpID
     ,Attendence.CardNo
      ,EmployeeDesignation.StrDesignationName
      ,EmployeeDept.StrDepartmentName
      -- Count data will be in one column
      ,(Select COUNT(*) From TestTable Where GEmployeeGenInfoID=Attendence.GEmployeeGenInfoID) TotalAbsent
      -- Row data set into one column seperate by coma
      ,substring( ( SELECT ', ' + dtAttendDateTime as [text()]
                       FROM TestTable 
                       WHERE  GEmployeeGenInfoID = Attendence.GEmployeeGenInfoID
                       FOR XML path(''), elements
                     ), 3, 1000
                    )  List
FROM 
     Payroll_tblAttendance as Attendence
     INNER JOIN TestTable on TestTable.GEmployeeGenInfoID=Attendence.GEmployeeGenInfoID
     INNER JOIN PIS.dbo.PIS_tblEmployeeGenInfo as EmployeeGenInfo ON Attendence.GEmployeeGenInfoID= EmployeeGenInfo.GEmployeeGenInfoID
     INNER JOIN PIS.dbo.PIS_tblDesignationInfo as EmployeeDesignation ON EmployeeGenInfo.GDesignationInfoID= EmployeeDesignation.GDesignationInfoID
     INNER JOIN PIS.dbo.PIS_tblDepartment as EmployeeDept ON EmployeeGenInfo.GDepartmentID= EmployeeDept.GDepartmentID
     WHERE EmployeeGenInfo.GFactoryID=@GFacatoryID AND Attendence.DayStatusID = 0 AND Attendence.dtAttendDateTime Between @FromDate and @ToDate
DROP TABLE TestTable
END