I have the following:
DECLARE @TABLE1 TABLE
(
VAL1 VARCHAR(2),
VAL2 VARCHAR(2)
)
INSERT INTO @TABLE1
VALUES ('A', 'X'), ('A', 'Y'), ('A', 'Z'),
('B', 'X'), ('B', 'Y'),
('C', 'X'), ('D', 'X')
And I want to get the following results:
1 A X
1 A Y
1 A Z
2 B X
2 B Y
3 C X
4 D X
What I did is this:
WITH T1 AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY VAL1) RW,
VAL1
FROM
@TABLE1
GROUP BY
VAL1
)
SELECT
T1.RW, T2.VAL1, T2.VAL2
FROM
T1
INNER JOIN
@TABLE1 T2 ON T1.VAL1 = T2.VAL1
It works, but I wonder if there is another easier way to do it?
Thanks for your help!
You can use dense_rank()
:
select dense_rank() over (order by val1) as rw, val1, val2
from @table1 t1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.