您可以尝试这种非三角形连接解决方案:
DECLARE @MyTable TABLE(
-- You should use appropiate data types for every column
[Time] VARCHAR(20) NOT NULL,
Department VARCHAR(20) NOT NULL,
WorkTitle VARCHAR(20) NOT NULL
);
INSERT INTO @MyTable ([Time],Department,WorkTitle)
SELECT 't1', 'Dep1', 'Wt1'
UNION ALL SELECT 't2', 'Dep1', 'Wt1'
UNION ALL SELECT 't3', 'Dep2', 'Wt2'
UNION ALL SELECT 't4', 'Dep2', 'Wt2'
UNION ALL SELECT 't5', 'Dep1', 'Wt1'
UNION ALL SELECT 't6', 'Dep3', 'Wt1'
UNION ALL SELECT 't7', 'Dep3', 'Wt1'
UNION ALL SELECT 't8', 'Dep3', 'Wt1';
DECLARE @ResultsWithRowNum TABLE
(
RowNum INT PRIMARY KEY,
[Time] VARCHAR(20) NOT NULL,
Department VARCHAR(20) NOT NULL,
WorkTitle VARCHAR(20) NOT NULL
);
INSERT @ResultsWithRowNum(RowNum,[Time],Department,WorkTitle)
SELECT ROW_NUMBER() OVER(ORDER BY x.[Time]) AS RowNum,x.[Time],x.Department,x.WorkTitle
FROM @MyTable x;
WITH RecursiveCTE
AS
(
SELECT crt.RowNum,
crt.[Time],
crt.Department,
crt.WorkTitle,
1 AS IsFirstRowNewGroup
FROM @ResultsWithRowNum crt
WHERE crt.RowNum=1
UNION ALL
SELECT crt.RowNum,
crt.[Time],
crt.Department,
crt.WorkTitle,
CASE WHEN prev.Department = crt.Department AND prev.WorkTitle = crt.WorkTitle THEN 0 ELSE 1 END
FROM @ResultsWithRowNum crt
INNER JOIN RecursiveCTE prev ON crt.RowNum = prev.RowNum + 1
)
SELECT *
FROM RecursiveCTE rec
WHERE rec.IsFirstRowNewGroup = 1
OPTION (MAXRECURSION 0);
结果:
RowNum Time Department WorkTitle IsFirstRowNewGroup
------ ---- ---------- --------- ------------------
1 t1 Dep1 Wt1 1
3 t3 Dep2 Wt2 1
5 t5 Dep1 Wt1 1
6 t6 Dep3 Wt1 1