• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 321
  • Last Modified:

Line count by group

For the life of me I can not remember how to do the following:

Given a table with the following:
ordr_sys_key_id, ordr_dt, locn_sys_key_id
1001, 2002/03/04, 305
1003, 2002/03/04, 305
1011, 2002/03/04, 305
1002, 2002/03/04, 306
1004, 2002/03/04, 306
1012, 2002/03/04, 306

I want ro produce something like this in a query:
1001 2002/03/04 305 1
1003 2002/03/04 305 2
1011 2002/03/04 305 3
1002 2002/03/04 306 1
1004 2002/03/04 306 2
1012 2002/03/04 306 3

Thanks,
Darek


0
dtomyn
Asked:
dtomyn
  • 2
1 Solution
 
Scott PletcherSenior DBACommented:
Something like this should do it:

SELECT ordr_sys_key_id, ordr_dt, locn_sys_key_id,
    (SELECT COUNT(*) + 1
     FROM tablex x2
     WHERE x1.locn_sys_key_id = x2.locn_sys_key_id
     AND x1.ordr_sys_key_id < x2.ordr_sys_key_id) AS 'Line#'
FROM tablex x1
ORDER BY locn_sys_key_id, ordr_sys_key_id

Notes:
*) this method may not perform very well on a really large table
*) haven't tested this yet -- will do so ASAP

0
 
Scott PletcherSenior DBACommented:
Oops, got some logic backwards.  In the WHERE, need to change "<" to ">".  Also, I didn't format the date properly.  Here is the corrected query:

SELECT ordr_sys_key_id, CONVERT(CHAR(10),ordr_dt,111) AS 'Order Date', locn_sys_key_id,
   (SELECT COUNT(*) + 1
    FROM tablex x2
    WHERE x1.locn_sys_key_id = x2.locn_sys_key_id
    AND x1.ordr_sys_key_id > x2.ordr_sys_key_id) AS 'Line#'
FROM tablex x1
ORDER BY locn_sys_key_id, ordr_sys_key_id
0
 
dtomynAuthor Commented:
Perfect (basically), thanks.
0
 
gchavezrCommented:
I´m just looking
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now