If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > First n records of each group

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-25-07, 10:26
arlf arlf is offline
Registered User
 
Join Date: May 2006
Posts: 16
First n records of each group

DB2 z/OS V8

CAR tbl ( 1 row by each car sold)
Cols => SYEAR : Sale Year
CYEAR : Car Year
MAKE : Car Manufacturer
MODEL: Car Model

Request: Select the ten most sold cars per year (between 2 given years)
SALE YEAR CYEAR-MAKE-MODEL COUNT
---------- -------------------- --------
2000 X10 CX10
X09 CX09
... ...
2001 Y10 CY10
Y09 CY09
... ...
2002 Z10 CZ10
Z09 CZ09
... ...

Thanks for your help, ARLF.
Reply With Quote
  #2 (permalink)  
Old 05-25-07, 10:37
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
sounds like homework

can we see your query?
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 05-25-07, 13:32
stolze stolze is offline
Registered User
 
Join Date: Jan 2007
Location: Jena, Germany
Posts: 2,662
Use the ROW_NUMBER function with the window-partitioning clause to number the rows in each group, then select all rows with a row number in the respective range.
__________________
Knut Stolze
IBM DB2 Analytics Accelerator
IBM Germany Research & Development
Reply With Quote
  #4 (permalink)  
Old 05-25-07, 15:07
arlf arlf is offline
Registered User
 
Join Date: May 2006
Posts: 16
Thanks Knut,
initially, the report was made with 2 programs using cursors, work files and sort (mainframe). However, I was looking for a solution that could be run under QMF.
Something like
SELECT syear, cyear, make, model, c1,
DENSE_RANK() OVER(PARTITION BY syear ORDER BY c1 DESC) AS r1
FROM ( SELECT syear, cyear, make, model, count(*) as c1
FROM car
WHERE syear BETWEEN 2000 AND 2007
GROUP BY syear, cyear, make, model ) AS T1
WHERE r1 < 11
ORDER BY syear, c1 desc;

Saludos, ARLF.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On