Home > Ask the Oracle Experts > Questions & Answers
Ask The Oracle Expert: Questions & Answers
EMAIL THIS

TOP query with multiple columns

Rudy Limeback EXPERT RESPONSE FROM: Rudy Limeback

Pose a Question
Other Oracle Categories
Meet all Oracle Experts
Become an Expert for this site
>
QUESTION POSED ON: 13 January 2005

Here is the table I am using. I want query for this. I tried with many queries but in vain.

Topics   XX   YY   ZZ   RR
------  ---- ---- ---- ----
ABCD    120   25   40   65
EFGH     10   15  200   40 
IJKL     35  250  125  145
MNOP     45  300  275  160

I want overall Top 'N' values for the above table. The maximum value in this table is 300, next is 275, next is 250, and so on. I want the result as follows:

MNOP YY 300
MNOP ZZ 275
IJKL YY 250
EFGH ZZ 200  
MNOP ZZ 160
IJKL RR 145
IJKL ZZ 125
ABCD XX 120
ABCD RR  65
...

>
EXPERT RESPONSE

You'll need a UNION query to produce a result set which contains all the values from each of the 4 columns in one result set column. Then you can do your "top N" query on the result set (which is called a derived table when used as a subquery).

Note that "top N" logic varies from one database to the next; see FIRST N rows, TOP N rows, LAST N rows, BOTTOM N rows...

Here's how it would look in SQL Server:

select top 10 
       Topics, source, sourcevalue
  from (
       select Topics
            , 'XX' as source, XX as sourcevalue
         from yourtable
       union all  
       select Topics, 'YY', YY 
         from yourtable
       union all  
       select Topics, 'ZZ', ZZ 
         from yourtable
       union all  
       select Topics, 'RR', RR 
         from yourtable
       ) as dt
order by sourcevalue desc

Note UNION ALL instead of UNION, because we do not want the result set scanned for duplicates.


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary



Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice

HomeNewsTopicsTipsAsk the ExpertsWebcastsWhite PapersProductsBlogs
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Reprints  |  Site Map




All Rights Reserved, Copyright 2003 - 2008, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts