Results 1 to 3 of 3

Thread: [RESOLVED] [SQL Server] - Query Distinct and Max or Function

  1. #1

    Thread Starter
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Resolved [RESOLVED] [SQL Server] - Query Distinct and Max or Function

    Hello

    I'm having some doubts to build a query (if it possible)...

    I have this table,
    idReg (PK + AutoInc), FieldFK, InternalNumber,Name,Qt
    ----------------------------------------------------------------------
    1 | 8 | 1111 | Prod1 | 123.3
    2 | 7 | 2222 | Prod2 | 222.2
    3 | 8 | 111A | Prod1Renamed | 100
    4 | 2 | 4444 | Pord9 | 12
    5 | 7 | 3333 | Prod2 | 333

    What i want from this table it's all the rows with Distinct FieldFK, with the idReg MAX...

    The query result would be (not necessarly by this order):
    3 | 8 | 111A | Prod1Renamed | 100
    4 | 2 | 4444 | Pord9 | 12
    5 | 7 | 3333 | Prod2 | 333

    I'm trying to build the query, but i don't get anywhere...
    Distinct only works if i only select the FieldFK if i had the other fields i get all the rows because it have distinct values for the other columns. What i need it's a kind of max for each FieldFK.

    Rate People That Helped You
    Mark Thread Resolved When Resolved

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [SQL Server] - Query Distinct and Max or Function

    You are on the right lines - what you want isn't a Distinct or any kind of Group By, and "a kind of max for each FieldFK." is pretty much it.

    The way to do that is to use a sub-query (using the same table) based on FieldFK, which you can do like this:
    Code:
    SELECT idReg, FieldFK, InternalNumber, Name, Qt
    FROM tableName as t1
    WHERE idReg = (SELECT Max(idReg)
                   FROM tableName
                   WHERE FieldFK = t1.FieldFK)
    By giving the table an alias in the main query, you can refer to the values from it in the sub-query, thus causing the sub-query to run for each row of the main query (and be linked to it).

  3. #3

    Thread Starter
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Re: [SQL Server] - Query Distinct and Max or Function

    Thanks, i allready manged to do the job, not equal to your solution but similar... Sometimes it helps writing the problem

    Resolved

    Rate People That Helped You
    Mark Thread Resolved When Resolved

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width