nth maximum but a little different

  • I have table as follows

    Acctid

    Tpid

    amt

    1

    1

    200

    1

    2

    180

    1

    3

    150

    2

    4

    120

    2

    5

    100

    2

    6

    80

    3

    7

    60

    3

    8

    40

    3

    9

    20

    I want those TPIDs  for each Acctid  which has the  top 2 amts

    So My query should show the result  as

    Acctid

    Tpid

    1

    1

    1

    2

    2

    4

    2

    5

    3

    7

    3

    8

    Can somebody help ?  It is urgent

     

    Regards

    Meghana

     

     


    Regards,

    Meghana

  • So, you're looking for the TOP 2 of each group? Try this:

    set nocount on

    use northwind

    select

    t1.CustomerID

    , t1.OrderDate

    from

    orders t1

    where

    t1.OrderDate in

    (

    select top 2 --with ties

    t2.OrderDate

    from

      orders t2

    where

      t2.CustomerID = t1.CustomerID

    order by

      t2.OrderDate desc

    )

    order by

    t1.CustomerID

    , t1.OrderDate desc

    set nocount off

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • I have another way to solve this.

     

    select CustomerID, Orderdate

    from orders A where A.Orderdate in

    (select Top 2 B.orderdate from orders B where A.customerId = B.customerId)

    order by CustomerID, OrderDate desc

     

    Which query is better  performance wise ? I have 370,000 rows in the table and I need top 100 data.

    please let me know which one is better so that I can use that query

     

    Regards

    Meghana


    Regards,

    Meghana

  • run both and see for yourself, just make sure you have all the indexes you need to run each query.

  • The only difference I see between your statement and mine, is that I do a SELECT TOP 2 ...ORDER BY ...DESC, while you don't. Both execution plans are the same, except for the sort for my ORDER BY.

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Btw, you should really add an ORDER BY when you select your TOP 2, otherwise your resultset is not predictable and meaningless.

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply