У меня есть следующий запрос для получения различных функций, областей и приоритета для сотрудника:
;with employeeScopeFunctions as
(
SELECT
e.employeeId,
es.FunctionId,
ef.Label,
c.CompanyName,
es.SortOrder
FROM
employee e
LEFT JOIN employee_scope es on es.employeeId = e.employeeId
LEFT JOIN employee_function ef on es.FunctionId = ef.FunctionId
LEFT JOIN Company c ON es.CompanyId = c.ID
WHERE
e.EmployeeId = 54
),
RankingBySum AS
(
SELECT
esf.EmployeeId,
esf.Label,
STUFF (
(
SELECT ',' + CompanyName
FROM employeeScopeFunctions es
WHERE esf.EmployeeId=es.EmployeeId AND esf.FunctionId=es.FunctionId
FOR XML PATH('')
)
, 1,1,'') AS Companies,
SUM(esf.SortOrder) as sumOrder,
SumRanking = ROW_NUMBER() OVER (PARTITION BY esf.EmployeeId ORDER BY SUM(esf.SortOrder) ASC)
FROM
employeeScopeFunctions esf
GROUP BY
esf.EmployeeId,
esf.FunctionId,
esf.Label
)
SELECT * FROM (SELECT
R.EmployeeId,
R.Label,
primacy = CASE R.SumRanking
WHEN 1 THEN 'primary'
WHEN 2 THEN 'secondary'
WHEN 3 THEN 'tertiary' END
FROM
RankingBySum AS R) t
PIVOT (
MAX(t.Label)
FOR t.primacy IN ([primary],[secondary],[tertiary])
) AS PVT
Вывод, который у меня есть:
EmployeeId primary secondary tertiary
54 Group Chief Executive Officer Group Regional Chief Executive Officer Director
Мой ожидаемый вывод, чтобы избежать дублированияэто собрать всю информацию в одну запись:
EmployeeId PrimaryFunction SecondaryFunction TertiaryFunction PrimaryCompanies SecondaryCompanies TertiaryCompanies
54 Group Chief Executive Officer Group Chief Executive Officer Director C1,C2,X5 X6,F6 VY,G7