home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / database / oracle / 2641 < prev    next >
Encoding:
Internet Message Format  |  1992-12-28  |  2.2 KB

  1. Path: sparky!uunet!zaphod.mps.ohio-state.edu!darwin.sura.net!gatech!destroyer!gumby!yale!hsdndev!dartvax!kip-sn-50.dartmouth.edu!user
  2. From: carl.pedersen@dartmouth.edu (L. Carl Pedersen)
  3. Newsgroups: comp.databases.oracle
  4. Subject: Top N Groups of Something [was Re: Explain THIS, please!]
  5. Message-ID: <carl.pedersen-281292114234@kip-sn-50.dartmouth.edu>
  6. Date: 28 Dec 92 17:15:32 GMT
  7. References: <1gtd91INN7ln@ef2007.efhd.ford.com> <1992Dec22.163411.557@hhcs.gov.au> <1992Dec23.150326.560@hhcs.gov.au>
  8. Sender: news@dartvax.dartmouth.edu (The News Manager)
  9. Followup-To: comp.databases.oracle
  10. Organization: Dartmouth College
  11. Lines: 41
  12.  
  13. In article <1992Dec23.150326.560@hhcs.gov.au>, geemic@hhcs.gov.au wrote:
  14. > In article <1992Dec22.163411.557@hhcs.gov.au>, champs@hhcs.gov.au writes:
  15. > > In article <1gtd91INN7ln@ef2007.efhd.ford.com>, wwm@ef5003.efhd.ford.com (Bill Meahan) writes:
  16. [stuff omitted]
  17. > > It looks to me like you're trying to retreive the 10 parts with the highest
  18. > > sum(cost).  As far as I can tell it's impossible to retrieve the top 10 groups
  19. > > of anything in a single query.  You can retrieve the top ten of something, but
  20. > > not the top 10 GROUPS of something.  Your only chance is to use PL/SQL cursors
  21.  
  22. I think it can be done without PL/SQL, if you are willing to use views (and
  23. why not).
  24.  
  25.  
  26.  create view part_count1 as
  27.  select part, count(*) count 
  28.    from part_usage_table
  29.   group by part;
  30.  
  31.  create view part_count as
  32.  select a.part, a.count, count(*) rank
  33.    from part_count1 a, part_count1 b
  34.   where b.count > a.count or
  35.         ( b.count = a.count and 
  36.           b.part <= a.part )
  37.   group by a.part, a.count;
  38.  
  39.  
  40.  select part, count from part_count where rank <=10 order by rank;
  41.  
  42. I tested this with a slightly different table of my own and it worked, so
  43. unless I've made a typo, the final select, above, should give the top ten
  44. most frequently used parts (incidentally, in order of usage).
  45.  
  46. Note that an arbitrary decision is made:  If two parts have the same
  47. frequency of use, then the one with the lower number is ranked earlier.
  48.  
  49. I make no claims that this is efficient.  A PL/SQL program might be able to
  50. do it faster.
  51.  
  52. I originally learned this technique from Martin Jensen at dde in Denmark.
  53.