Tuesday, May 17, 2005

How to create an enumeration or position of a child table record

I have seen this question in many user forums. Lets consider pubs database in MS-SQL SERVER. Now see how to generate the position number of each titles of an author in the titleauthor table.


SELECT * FROM
(
SELECT
( SELECT COUNT(au_Id)
FROM titleauthor a
WHERE a.au_Id = b. au_Id
AND a.title_ID <= b.title_ID
) as pos ,
au_Id,
title_ID
FROM titleauthor b
GROUP BY au_Id ,title_ID
) T

ORDER BY au_Id

This is the result we get


pos au_Id title_ID
--------------------------------------
1 172-32-1176 PS3333
1 213-46-8915 BU1032
2 213-46-8915 BU2075
1 238-95-7766 PC1035
1 267-41-2394 BU1111
2 267-41-2394 TC7777
1 274-80-9391 BU7832
1 409-56-7008 BU1032
1 427-17-2319 PC8888
1 472-27-2349 TC7777
1 486-29-1786 PC9999
2 486-29-1786 PS7777
1 648-92-1872 TC4203
1 672-71-3249 TC7777
1 712-45-1867 MC2222
1 722-51-5454 MC3021
1 724-80-9391 BU1111
2 724-80-9391 PS1372
1 756-30-7391 PS1372
1 807-91-6654 TC3218
1 846-92-7186 PC8888
1 899-46-2035 MC3021
2 899-46-2035 PS2091
1 998-72-3567 PS2091
2 998-72-3567 PS2106

=====================================

1 comment:

Anonymous said...

Its a new and brave logic. I really apreciate that. Keep it up.
Please include the actual table contents for the better understandings. I am in favour of oracle, dont know the tables in pubs database in SQL server.