DROP TABLE IF EXISTS #SalaryData
CREATE TABLE #SalaryData (
Id INT NOT NULL PRIMARY KEY IDENTITY,
EmployeeId INT NOT NULL,
SalaryDate DATETIME CONSTRAINT DF__SalaryData__SalaryDate DEFAULT (GETUTCDATE()),
Salary DECIMAL(19,4) NOT NULL CONSTRAINT DF__SalaryData__Salary DEFAULT (0.0)
)
INSERT #SalaryData(EmployeeId, Salary)
VALUES
(2, 30000.0),
(1, 40000.0),
(5, 40000.0),
(3, 30000.0),
(4, 19000.0)
-- Просто выборка по зарплате
SELECT *
FROM #SalaryData sd
ORDER BY sd.Salary DESC
-- Выборка зарплат и сотрудников, у которых зарплата больше чем у целевого сотрудника
;WITH CTE AS
(
SELECT
RootEmployeeId = sd.EmployeeId,
sd.EmployeeId,
sd.Salary,
Depth = 0
FROM #SalaryData sd
UNION ALL
SELECT
RootEmployeeId = cte.EmployeeId,
sd.EmployeeId,
sd.Salary,
Depth = cte.Depth + 1
FROM CTE cte
INNER JOIN #SalaryData sd ON sd.Salary > cte.Salary
)
SELECT
cte.RootEmployeeId,
STRING_AGG(CONCAT(cte.Salary, ' (', cte.EmployeeId, ')'), ', ') WITHIN GROUP (ORDER BY cte.Salary ASC)
FROM CTE cte
WHERE cte.Depth < 2
GROUP BY cte.RootEmployeeId