Results 1 to 7 of 7

Thread: how to use the MAX function in SQL server?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    257

    how to use the MAX function in SQL server?

    I want the entire row with those 4 fields returned with the highest attempt number for this statement:

    SELECT DISTINCT UserID, QuizID, AttemptNum, DateSaved
    FROM tblResults
    WHERE (QuizID = 5) AND (UserID = 4)

    couldda swarn in real SQL (aka not microsoft's stupid SQL) you can just wrap the AttemptNum in a MAX() clause in the select clause but I guess not. What's the way to do it in their stupid language if they even left a way to do it at all.
    I tried to end process on Visual Studio 2005
    but PETA stopped me saying it's smart enough
    to be a living creature

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

    Re: how to use the MAX function in SQL server?

    "microsoft's stupid SQL" as you call it, is real SQL - it follows the standards of SQL 92, whereas whatever system(s) you used before appear to have used their own standards.

    In order to return a calculated value (eg: Max or Count) as part of your query results, you use a Group By like this:
    Code:
    SELECT UserID, QuizID, Max(AttemptNum), DateSaved
    FROM tblResults
    WHERE (QuizID = 5) AND (UserID = 4)
    GROUP BY UserID, QuizID, DateSaved
    ..note that the Max wil only apply to the rows that have the same values of UserID, QuizID, and DateSaved.

    An alternative (which is not supported by all DBMS's) is to put a sub-query directly into the Select list like this:
    Code:
    SELECT DISTINCT UserID, QuizID, (SELECT Max(AttemptNum) FROM tblResults), DateSaved
    FROM tblResults
    WHERE (QuizID = 5) AND (UserID = 4)

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    257

    Re: how to use the MAX function in SQL server?

    the version of SQL I use is the one in my SQL book that claims it's universal to all DMBS's and is a pretty recent printing. We practice it on OS400 on an IBM iSeries which btw were invented in 1980 and haven't changed much since. I used the nested query version you got there but I shouldn't have had to. If I had data like this:
    UserID QuizID, AttemptNum, DateSaved
    1 | 3 | 1 | 10/15/2006
    2 | 3 | 2 | 10/15/2006

    which UserID would appear on the returned row with your triple group by statement? The date saved and the quiz ID would try to group because they're similar but what would happen to the User ID? If it left them both there then I'd have two rows so that's the same as not using group by at all. If it just took the first one that'd be a really inaccurate way to do it. If it took the highest (or lowest) value that's not always the best way depending on the circumstances. If it left it null or removed that column that'd be useless. If it just randomly picked, that'd be stupid. I don't see how doing group by on all columns could do anything at all. So far I've used 3 DBMS's and 2 and possibly the third one of them all use group by on single columns and distinct with ()'s.
    I tried to end process on Visual Studio 2005
    but PETA stopped me saying it's smart enough
    to be a living creature

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: how to use the MAX function in SQL server?

    There's really no such thing as "universal" SQL. There is an SQL standard but no database adhere's to the standard in all situations. Having said that, "SQL in a Nutshell" provides the SQL2003 standard and it also provides information on each platforms individual variations. My copy of "SQL in a Nutshell" clearly states
    Include all non-aggregate columns in the GROUP BY clause.
    That's pretty clear. Any database that doesn't follow that rule is not following the SQL2003 standard. Does that make them the stupid ones? Also, MSDN has a full T-SQL reference so you can go and see their stupid implementation for yourself. No database worth its salt follows the SQL standard completely because they have all added variations and additions that they consider make their implementation easier or better. That's ALL databases. If things don't work the way you expect don't assume that your tools are stupid. Assume that you're making invalid assumptions.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: how to use the MAX function in SQL server?

    SQL Server uses ANSI 92 structured query language as its standard. Other database manufacturers use ANSI 92 also as well as some unique one off "standards". ANSI has a few standards that the database manufacturers can decide to use or not. Its up to them. Even Access uses ANSI 89 standards by default.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Oct 2005
    Posts
    257

    Re: how to use the MAX function in SQL server?

    I dunno about that cuz adding columns to a group by clause that you specifically don't want to be grouped together when duplicated values are found is pretty much the definition of stupid. A LOT of things about most BDMS's are stupid. Running DISTINCTS on primary key fields instead of filtering those clauses out, preset resource wasting field sizes, changing SQL in general, useless error messages, wasted space on deleted data, the need for commit statements for stupid programmers that don't verify data before sending it, the manualness and disc choosing on mainframes, and the fact that anyone still uses DB2/AS400s at all. I hate databases, I think we as programmers should boycott them. Take a look at winsite.com or download.com or even just AIM Triton and tell me we don't need more quality software engineers working on writing utilities instead.
    I tried to end process on Visual Studio 2005
    but PETA stopped me saying it's smart enough
    to be a living creature

  7. #7
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: how to use the MAX function in SQL server?

    Quote Originally Posted by A SQL Hater
    I want the entire row with those 4 fields returned with the highest attempt number for this statement:
    Start thinking in set-based logic and your request is quite simple.

    Code:
    Select UserID, QuizId, AttemptNum, DateSave
       From tblResults TR1
       Where QuizId=5 and UserId=4
             and AttemptNum=(Select Max(TR2.AttemptNum) From tblResults TR2
                               Where TR2.UserId=TR1.UserId and TR2.QuizId=TR1.QuizId)
    GROUP BY and DISTINCT will never serve the need you asked about. You are looking for a particular row - not looking to aggregate anything in the working resultset.

    btw - MS SQL SERVER is not a MS product at all. They purchased it from SYBASE - makers of SQL products that ran on mainframes from probably 1950!

    If you keep bashing SQL in your questions here then some of us might stop wanting to answer your questions

    It's all good - and it's all understandable - and we all are willing to help.
    Last edited by szlamany; Oct 16th, 2006 at 07:59 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

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