在此处输入图像描述我想创建一个视图,它具有一些列,并且所有行具有相同的结果(除了一个列之外),如何合并或合并一行中的所有行,但一列具有我想要的不同值将它们显示在一列中,并用逗号分隔值。 如果有办法通过Query告诉我。
CREATE VIEW [ret_vwSalaried]
AS
SELECT
salaried.FirstName,
salaried.LastName,
salaried.IdNumber,
salaried.PersonnelNumber,
operation.OperationalUnit
FROM
ret_Salaried salaried INNER JOIN
ret_OperationalUnitFeaturs operation ON salaried`enter code here`.Guid = operation.SalariedGuid
WHERE Deleted = 0
结果包括3行,我想将它们合并为一行,因为它们相同,但是[OperationalUnit]列的结果不同(每个人的操作单元可能不同),我也想将它们合并行并用逗号分隔。
答案 0 :(得分:0)
CREATE VIEW [dbo].[ret_vwSalariedForReport]
AS
WITH temp1 AS (SELECT
salaried.*,
operationalUnits.Title as OperationalUnitTitle
FROM
ret_vwSalaried salaried LEFT JOIN
prs_operationalUnitFeatures operationalUnitFeatures on salaried.[Guid] = operationalUnitFeatures.[FeatureGuid] LEFT JOIN
prs_operationalUnits operationalUnits ON operationalUnits.id = operationalUnitFeatures.OperationalUnitID
),
temp2 AS (SELECT
t2.*,
STUFF ((SELECT ' - ' + t1.OperationalUnitTitle
FROM
temp1 t1
WHERE t1.[ID] = t2.[ID]
For XML PATH('')), 2, 2, '') OperationalUnitTitles from temp1 t2)
SELECT
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles
FROM
temp2
GROUP BY
[Guid],
ID,
Title,
PersonnelNo,
FirstName,
LastName,
FullName,
Active,
SSN,
DeathDate,
SalariedType,
OperationalUnitTitles