sql-server - sqlserver - sql server management studio下载



逗号根据公司ID分隔的名字 (2)

你可以使用这个查询:

SELECT EmployeeNames = dbo.EmployeeNamesPerCompany(CompanyID,', '), 
       CompanyID, 
       CompanyLastActive = MAX(CompanyLastActive)
FROM Employee e
GROUP BY CompanyID
ORDER BY MAX(CompanyLastActive)

如果你已经创建了这样的标量值函数:

CREATE FUNCTION [dbo].[EmployeeNamesPerCompany]
(
    @companyID Int,
    @delimiter varchar(5)
)
RETURNS VARCHAR(8000)
AS
BEGIN
    DECLARE @Names VARCHAR(8000) 
    SELECT   @Names = COALESCE(@Names + @delimiter, '') + e.EmployeeName
    FROM    Employee e
    WHERE e.CompanyId = @companyID
    ORDER BY e.EmployeeName
    return @Names
END

Sql-Fiddle演示

我有下面的员工详细信息表

EmployeeName   CompayId    CompanyLastActive
---------------------------------------------------------
robort          112        10 Jun 2015 09:30 
john            113        11 Jun 2015 11:10
sunny           114        14 Jun 2015 16:10
sumanth         114        15 Jun 2015 18:11
usha            115        07 Jun 2015 13:14
sudheer         115        14 Jun 2015 17:10
sweety          115        08 Jun 2015 16:34

我需要根据CompanyID获取最新的员工活动时间,并使用逗号分隔的EmployeeName,如下所示

EmployeeName           CompayId        CompanyLastActive
---------------------------------------------------------
robort                 112               10 Jun 2015 09:30 
john                   113               11 Jun 2015 11:10
sunny, sumanth         114               15 Jun 2015 18:11        
usha, sudheer, sweety   115               14 Jun 2015 17:10

请帮我解决。


Answer #1
SELECT EmployeeName = STUFF((
          SELECT ',' + e1.EmployeeName
          FROM dbo.Employee e1
          WHERE e.CompayId = e1.CompayId
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
        e.CompayId,
        MAX(CompanyLastActive) as CompanyLastActive
FROM dbo.Employee e
GROUP BY e.CompayID
ORDER BY e.CompayId

结果:

EmployeeName        CompayId    CompanyLastActive
-------------------------------------------------------
robort              112         June, 10 2015 09:30:00
john                113         June, 11 2015 11:10:00
sunny,sumanth       114         June, 15 2015 18:11:00
usha,sudheer,sweety 115         June, 14 2015 17:10:00

SQL小提琴中的示例结果。





sql-server-2012