问题描述
我有以下结果集,
现在有了以上结果,我想通过选择查询打印记录,如下图所示
请注意,我将在输出当前员工和缺勤员工中只有两种类型的列。
我尝试使用数据透视表、临时表,但无法实现我想要的。
解决方法
一种方法是 ROW_NUMBER
每个“状态”,然后使用 FULL OUTER JOIN
将 2 个数据集放入适当的列中。我使用 FULL OUTER JOIN
,因为我假设您可能有不同数量的员工在场/缺席。
CREATE TABLE dbo.YourTable (Name varchar(10),--Using a name that doesn't require delimit identification
Status varchar(7),--Using a name that doesn't require delimit identification
Days int);
GO
INSERT INTO dbo.YourTable(Name,Status,Days)
VALUES('Mal','Present',30),('Jess',20),('Rick','Absent',('Jerry',10);
GO
WITH RNs AS(
SELECT Name,Days,ROW_NUMBER() OVER (PARTITION BY Status ORDER BY Days DESC) AS RN
FROM dbo.YourTable)
SELECT P.Name AS PresentName,P.Days AS PresentDays,A.Name AS AbsentName,A.Days AS AbsentDays
FROM (SELECT R.Name,R.Days,R.Status,R.RN
FROM RNs R
WHERE R.Status = 'Present') P
FULL OUTER JOIN (SELECT R.Name,R.RN
FROM RNs R
WHERE R.Status = 'Absent') A ON P.RN = A.RN;
GO
DROP TABLE dbo.YourTable;
2 CTE 实际上要整洁得多:
WITH Absents AS(
SELECT Name,ROW_NUMBER() OVER (ORDER BY Days DESC) AS RN
FROM dbo.YourTable
WHERE Status = 'Absent'),Presents AS(
SELECT Name,ROW_NUMBER() OVER (ORDER BY Days DESC) AS RN
FROM dbo.YourTable
WHERE Status = 'Present')
SELECT P.Name AS PresentName,A.Days AS AbsentDays
FROM Absents A
FULL OUTER JOIN Presents P ON A.RN = P.RN;