我的临时表解决方案。
-- Create a temp table, containing an extra column, ID
DECLARE @orderedPlans
(
ID int,
Plan varchar(64),
YrMth int
)
-- Use contents of your table, plus ROW_NUMBER, to populate
-- temp table. ID is sorted on Plan and YrMth.
--
INSERT INTO
@orderedPlans
(
ID,
Plan,
YrMth
)
SELECT ROW_NUMBER() OVER (ORDER BY Plan, YrMth) AS ID,
Plan,
YrMth
FROM
YourTable
-- Now join your temp table on itself
-- Because of the ROW_NUMBER(), we can use ID - 1 as a join
-- Also join on Plan, so that the query can handle multiple plans being
-- in the table
SELECT
p1.Plan,
p1.YrMth AS StartDate,
p2.YrMth AS EndDate
FROM
@orderedPlans p1
LEFT JOIN
@orderedPlans p2
ON
p1.Plan = p2.Plan
AND p1.ID = p2.ID - 1