我认为您需要重新设计您的架构,因为这对我来说似乎有点不愉快。
但是,如果您真的想这样做,那么以下查询将起作用:
;WITH cte([id],[gname1],[gname2],[date1],[order1])
AS
(
SELECT 1 [id], NULL [gname1], NULL [gname2], 'data 1' [date1], 1 [order1]
UNION ALL SELECT 5, 'red', NULL, 'data 5', 2
UNION ALL SELECT 4, 'blue', NULL, 'data 4', 3
UNION ALL SELECT 6, 'blue', NULL, 'data 6', 4
UNION ALL SELECT 3, 'blue', 'color1', 'data 3', 5
UNION ALL SELECT 8, 'blue', 'color2', 'data 8', 8
UNION ALL SELECT 2, 'red', NULL, 'data 2', 6
UNION ALL SELECT 7, NULL, NULL, 'data 7', 7
)
SELECT
[id]
,[gname1]
,[gname2]
,[date1]
,DENSE_RANK() OVER(ORDER BY [order1]) [order1]
FROM
(
SELECT
x.[id]
,x.[gname1]
,x.[gname2]
,x.[date1]
,MIN(ISNULL(y.order1, x.order1)) [order1]
FROM
cte x
LEFT OUTER JOIN
cte y
ON
x.gname1 IS NOT NULL
AND
x.gname1 = y.gname1
AND
ISNULL(x.gname2, '') = ISNULL(y.gname2, '')
GROUP BY
x.[id],x.[gname1],x.[gname2],x.[date1]
) z