2

How to write a query that will match data and produce and identity for it.

For Example:

RecordID | Name
1        | John
2        | John
3        | Smith
4        | Smith
5        | Smith
6        | Carl

I want a query which will assign an identity after matching exactly on Name.

Expected Output:

RecordID | Name  | ID
1        | John  | 1X
2        | John  | 1X
3        | Smith | 1Y
4        | Smith | 1Y
5        | Smith | 1Y
6        | Carl  | 1Z

Note: The ID should be unique for every match. Also, it can be numbers or varchar.

Can somebody help me with this? The main thing is to assign the ID's.

Thanks.

4

3 に答える 3

2

How about this:

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

The first part is for testing purposes only.

于 2013-03-11T21:26:27.793 に答える
1

してみてください:

SELECT *,
Rank() over (order by Name ASC) 
FROM table
于 2013-03-11T21:09:00.660 に答える
1

This structure seems to work:

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;
于 2013-03-11T21:29:52.273 に答える