Draken Draken - 1 year ago 111
SQL Question

Oracle SQL - Give each row in a result set a unique identifier depending on a value in a column

I have a result set, being returned from a view, that returns a list of items and the country they originated from, an example would be:

ID | Description | Country_Name
1 | Item 1 | United Kingdom
2 | Item 2 | France
3 | Item 3 | United Kingdom
4 | Item 4 | France
5 | Item 5 | France
6 | Item 6 | Germany

I wanted to query this data, returning all columns (There are more columns than
, I've omitted them for brevity's sake) with an extra one added on giving a unique value depending on the value that is inside the field

ID | Description | Country_Name | Country_Relation
1 | Item 1 | United Kingdom | 1
2 | Item 2 | France | 2
3 | Item 3 | United Kingdom | 1
4 | Item 4 | France | 2
5 | Item 5 | France | 2
6 | Item 6 | Germany | 3

The reason behind this, is we're using a Jasper report and need to show these items with an asterisk next to it (Or in this case a number) explaining some details about the country. So the report would look like this:

Desc. Country
Item 1 United Kingdom(1)
Item 2 France(2)
Item 3 United Kingdom(1)
Item 4 France(2)
Item 5 France(2)
Item 6 Germany(3)

And then further down the report would be a field stating:

1: Here are some details about the UK
2: Here are some details about France
3: Here are some details about Germany

I'm having difficulty trying to generate a unique number to go along side each country, starting at one each time the report is ran, incrementing it when a new country is found and keeping track of where to assign it. I would hazard a guess at using temporary tables to do such a thing, but I feel that's overkill.


  1. Is this kind of thing possible in Oracle SQL or am I attempting to do something that is rather large and cumbersome?

  2. Are there better ways of doing this inside of a Jasper report?

At the moment, I'm looking at just having the subtext underneath each individual item and repeating the same information several times, just to avoid this situation, rather than having them aggregated and having the subtext once. It's not clean, but it saves this rather odd hassle.

Answer Source

You are looking for dense_rank():

select t.*, dense_rank() over (order by country_name) as country_relation
from t;

I don't know if this can be done inside Jasper reports. However, it is easy enough to set up a view to handle this in Oracle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download