views:

36

answers:

2
+1  Q: 

SQL - sub count

Hi I've got some SQL ...

SELECT  
    AdviceNo,
    Registration
FROM tblSalesDetail

that produces something like ...

ADV00001, ABC123
ADV00001, CDE564
ADV00002, FGE432
ADV00003, HUY789
ADV00003, MJS532
ADV00003, JFY428

Can anyone tell me how I'd adjust it to see the following please?

ADV00001, ABC123, 1
ADV00001, CDE564, 2
ADV00002, FGE432, 1
ADV00003, HUY789, 1
ADV00003, MJS532, 2
ADV00003, JFY428, 3
+1  A: 

How's about Oracle Analytical Functions?

This is a classical example in which RANK is useful ;-)

SELECT AdviceNo,
       Registration,
       RANK () OVER (PARTITION BY AdviceNo ORDER BY Registration ASC) MY_RANK
  FROM tblSalesDetail;
The chicken in the kitchen
My solution works only under Oracle PL/SQL.
The chicken in the kitchen
Quite a few other DBs support partition by. SQL Server does and I'm pretty sure DB/2 does as well. There may be slight platform variations.
ConcernedOfTunbridgeWells
Mr Chicken, your solution works fine in MS SQL 2005 - thank you
Andy Clarke
Most of the OP's questions are about .Net and WPF so I guess he's probably using SQL Server. Note that the equivalent to RANK() in the T-SQL world is row_number().
ConcernedOfTunbridgeWells
+2  A: 

You can use row_number() and partition by with an over clause to reset a count based on groups; the syntax is something like (note, not tested):

SELECT  
    AdviceNo,
    Registration,
    row_number() over
    (partition by AdviceNo
     order by Registration)     as Ordinal
FROM tblSalesDetail

partition by is a bit like group by but it doesn't roll up the data - it just resets whatever you are calculating within the partition. In this case we are computing a row number using a built in function, and sorting it by Registration within the groups.

This link to the MSDN docs discusses using OVER on T-SQL. It's basically the same on other platforms that support it.

ConcernedOfTunbridgeWells
thanks for the explanation, thats helpful.
Andy Clarke