tags:

views:

63

answers:

3

I have a table with two columns n integer and s varchar. n is the primary key. s is mostly unique but not always. For example

n   s
1   New York
2   Moscow
3   Paris
4   London
5   Moscow
6   Berlin
7   Moscow

I want to create another table with the same structure, the same number of rows except that s will be made unique by adding numeric suffix to second and further occurences. Example:

n   s
1   New York
2   Moscow
3   Paris
4   London
5   Moscow 2
6   Berlin
7   Moscow 3

In a single SQL command in a platform independent way (sqlite is my database). Any ideas?

+3  A: 

SELECT e.ID, e.Name, (SELECT COUNT(*) FROM Table1 as d WHERE d.ID < e.ID AND d.Name = e.Name) FROM Table1 as e;

Horacio N. Hdez.
That's going to give you the same number for count for each name instance...
OMG Ponies
It works. Thanks.
danatel
you are welcome, sorry i not givin you the concat part, but i dont have any database right now.
Horacio N. Hdez.
A: 

why not just always add the primary key value to the beginning (or end) of the string? Then you can always sub string the string by the length of the primary key so you can always get the exact string you want.

so your data could look like:

n   s
1   1New York
2   2Moscow
3   3Paris
4   4London
5   5Moscow
6   6Berlin
7   7Moscow
.
.
.
100995 100995Paris
northpole
I want to send the strings over slow network and the strings must be human readable. So the suffixes should be minimal.
danatel
A: 

You haven't posted the real problem here and my guess is that there is a MUCH better solution to that then what you want to do. That being said, the code below should give you what you want. Use it at your own peril.

I've been using MS SQL almost exclusively lately, but I think that this is mostly ANSI compatible. The exception would be the RTRIM function. There is a TRIM function in the ANSI standards, but that doesn't seem to be supported in Transact-SQL, which uses RTRIM and LTRIM.

SELECT
     n,
     RTRIM(s + ' ' + COALESCE
     (
          (
          SELECT
               NULLIF(CAST(COUNT(*) AS VARCHAR(10)), 0) AS cnt
          FROM
               Some_Table T2
          WHERE
               T2.s = T1.s AND
               T2.n < T1.n
          ), ''
     )) AS s
FROM
     Some_Table T1

P.S. - If those are your real column names, your naming convention for the columns is horrible. ;)

Tom H.
Thanks, this is in principle the same as the solution from Horacio N. Hdez. The column names are not real. The real application sends strings over network using preexisting protocol which must be human readable. But for some reasons the receiving side must be able to reconstruct the key back.
danatel