我認爲這是你在找什麼
DECLARE @Table TABLE
(
Name VARCHAR(20),
Value INT
);
;WITH T AS (
SELECT CONCAT('a',1) AS Name, 1 AS Value
UNION ALL
SELECT CONCAT('a',T.Value + 1) AS Name, T.Value + 1 FROM T
WHERE T.Value < 5
)
INSERT INTO @Table
SELECT T.Name ,
T.Value
FROM T
INSERT INTO @Table
(Name, Value)
VALUES ('a5', -- Name - varchar(20)
5 -- Value - int
),('a5', -- Name - varchar(20)
5 -- Value - int
)
INSERT INTO @Table
SELECT * FROM @Table
INSERT INTO @Table
SELECT * FROM @Table
SELECT
COUNT(*) AS TotalCount
, Name
, Value
FROM
@Table
GROUP BY
Name ,
Value
ORDER BY
Name
DELETE T
FROM (
SELECT
Name
, Value
, ROW_NUMBER() OVER(PARTITION BY Name, Value ORDER BY Value) AS RN
FROM
@Table
) AS T
WHERE T.RN > 1
SELECT * FROM @Table ORDER BY Name, Value
注意:CONCAT()可能不適用於低於2012的SQL Server版本。 –