我喜欢使用窗口函数,因此我使用了简单的row_number()函数根据employeeID拆分一些数据。我写的东西行得通,但我不禁想到可以使用PIVOT编写。这是代码:-
WITH [Roles] AS
(
SELECT a.EmployeeID, a.StaffRole,
ROW_NUMBER() OVER (PARTITION BY a.EmployeeID ORDER BY a.StaffRole) AS RowNum
FROM [GCHHS_Reporting].[dbo].[CathLab_Staff] a
)
SELECT a.EmployeeID, b1.StaffRole AS SR#1, b2.StaffRole AS SR#2, b3.StaffRole AS SR#3, b4.StaffRole AS SR#4, b5.StaffRole AS SR#5 FROM [GCHHS_Reporting].[dbo].[CathLab_Staff] a
INNER JOIN [Roles] b1
ON a.EmployeeID = b1.EmployeeID AND b1.RowNum = 1
LEFT JOIN [Roles] b2
ON a.EmployeeID = b2.EmployeeID AND b2.RowNum = 2
LEFT JOIN [Roles] b3
ON a.EmployeeID = b3.EmployeeID AND b3.RowNum = 3
LEFT JOIN [Roles] b4
ON a.EmployeeID = b4.EmployeeID AND b4.RowNum = 4
LEFT JOIN [Roles] b5
ON a.EmployeeID = b5.EmployeeID AND b5.RowNum = 5
上面的代码显示自开始以来每个员工所担任的角色。所以,我的问题是;有PIVOT这样的方法吗?
以下是原始数据的示例:-
以下是窗口功能数据的示例:-
任何想法或我是如何做到的,最好的方法?
答案 0 :(得分:1)
是的,这比对表进行5次扫描要容易得多。与使用PIVOT
相比,我发现一些条件聚合要容易得多:
WITH [Roles] AS(
SELECT CLS.EmployeeID,
CLS.StaffRole,
ROW_NUMBER() OVER (PARTITION BY CLS.EmployeeID ORDER BY CLS.StaffRole) AS RowNum
FROM [GCHHS_Reporting].[dbo].[CathLab_Staff] CLS --a? CathLab doesn't start with "a".
)
SELECT R.EmployeeID,
MAX(CASE R.RowNum WHEN 1 THEN R.StaffRole END) AS SR1,
MAX(CASE R.RowNum WHEN 2 THEN R.StaffRole END) AS SR2,
MAX(CASE R.RowNum WHEN 3 THEN R.StaffRole END) AS SR3,
MAX(CASE R.RowNum WHEN 4 THEN R.StaffRole END) AS SR4,
MAX(CASE R.RowNum WHEN 5 THEN R.StaffRole END) AS SR5
FROM Roles R --nor does Roles begin with a "b"
GROUP BY R.EmployeeID;
我无法针对您的数据对此进行测试(因为它是图像),但是我做了一个小样本,返回的结果是在之后。 db<>fiddle
答案 1 :(得分:0)
PIVOT
确实很有意义。在您的简单示例中,Larnu提到一个case语句就足够了。