如何编写一个匹配数据并为其生成和标识的查询。
例如:
RecordID | Name 1 | John 2 | John 3 | Smith 4 | Smith 5 | Smith 6 | Carl
我想要一个查询,它会在完全匹配名称后分配一个身份。
预期产出:
RecordID | Name | ID 1 | John | 1X 2 | John | 1X 3 | Smith | 1Y 4 | Smith | 1Y 5 | Smith | 1Y 6 | Carl | 1Z
注意:每个匹配的ID都应该是唯一的。此外,它可以是数字或varchar。
有人可以帮我这个吗?主要是分配ID。
感谢。
答案 0 :(得分:2)
这个怎么样:
with temp as
(
select 1 as id,'John' as name
union
select 2,'John'
union
select 3,'Smith'
union
select 4,'Smith'
union
select 5,'Smith'
union
select 6,'Carl'
)
SELECT *, DENSE_RANK() OVER
(ORDER BY Name) as NewId
FROM TEMP
Order by id
第一部分仅用于测试目的。
答案 1 :(得分:1)
请尝试:
SELECT *,
Rank() over (order by Name ASC)
FROM table
答案 2 :(得分:1)
这种结构似乎有效:
CREATE TABLE #Table
(
Department VARCHAR(100),
Name VARCHAR(100)
);
INSERT INTO #Table VALUES
('Sales','michaeljackson'),
('Sales','michaeljackson'),
('Sales','jim'),
('Sales','jim'),
('Sales','jill'),
('Sales','jill'),
('Sales','jill'),
('Sales','j');
WITH Cte_Rank AS
(
SELECT [Name],
rw = ROW_NUMBER() OVER (ORDER BY [Name])
FROM #Table
GROUP BY [Name]
)
SELECT a.Department,
a.Name,
b.rw
FROM #Table a
INNER JOIN Cte_Rank b
ON a.Name = b.Name;