简体   繁体   中英

how to set unique name of each distinct values of a column in sql

I have a table testTble with column testVal which is containing duplicate value. I can find the each unique value of the column using DISTINCT(testVal) . But I want to set a specific name of each unique value of the column.

Like:

I run the query in my db and found those distinct value.

SELECT DISTINCT(testVal) AS web FROM `testTble`

Output:

web
169.254.15.169
10.0.0.91
192.168.80.47
10

Now I want to set a unique name of those values like this:

169.254.15.169 as web21 10.0.0.91 as web22

So how can I set a name like this?

In MySQL 8+, you can use row_number() :

select test_val, row_number() over (order by test_val)
from t
group by test_val;

In earlier versions, you can use variables:

select test_val, (@rn := @rn + 1) as seqnum
from t cross join
     (select @rn := 0) params
group by test_val;

In both cases, the "name" is a numeric value, but that seems consistent with what you want to do.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM