Home > Net >  Create a new column, grouping info from other columns in Teradata
Create a new column, grouping info from other columns in Teradata

Time:02-26

Having this:

BEGIN TRANSACTION;

CREATE TABLE MY_TABLE(Salary integer, Name text, Country text);

INSERT INTO MY_TABLE VALUES(10,'Tom', 'Albania');
INSERT INTO MY_TABLE VALUES(20,'Lucy', 'Bulgaria');
INSERT INTO MY_TABLE VALUES(30,'Frank', 'Bulgaria');
INSERT INTO MY_TABLE VALUES(30,'Jane', 'Canada' );
INSERT INTO MY_TABLE VALUES(50,'Robert', 'Canada');
INSERT INTO MY_TABLE VALUES(50,'Robert2', 'Canada');
INSERT INTO MY_TABLE VALUES(100,'Robert2', 'Canada');
INSERT INTO MY_TABLE VALUES(50,'Robert3', 'Canada');
INSERT INTO MY_TABLE VALUES(60,'Robert6', 'Denmark');

COMMIT;

SELECT Salary, Name, Country,Salary || Country AS 'New' FROM MY_TABLE
WHERE Salary < 100

Producing this:

Salary Name Country New
10 Tom Albania 10Albania
20 Lucy Bulgaria 20Bulgaria
30 Frank Bulgaria 30Bulgaria
30 Jane Canada 30Canada
50 Robert Canada 50Canada
50 Robert2 Canada 50Canada
50 Robert3 Canada 50Canada
60 Robert6 Denmark 60Denmark

The question: Instead of the value in New, I want to have a subsequent number, that is the same for all equal strings. E.g., something like this:

Salary Name Country New
10 Tom Albania 1
20 Lucy Bulgaria 2
30 Frank Bulgaria 3
30 Jane Canada 4
50 Robert Canada 5
50 Robert2 Canada 5
50 Robert3 Canada 5
60 Robert6 Denmark 6

The number 5 is the same, because 50Canada is repeated 3 times in the table above.

CodePudding user response:

You can try to use dense_rank window function.

SELECT *,dense_rank() OVER(ORDER BY Salary,Country) new
FROM MY_TABLE
WHERE Salary < 100
  • Related