开发者

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


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜