Latest Date in a group function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sarah2855
    New Member
    • May 2010
    • 21

    Latest Date in a group function

    I have a table that looks like this:
    CustomerID ProductOrdered OrderDate OrderQuantity
    0001 ProdA 1/1/2007 3
    0001 ProdA 1/1/2008 2
    0002 ProdB 1/1/2006 1


    I'm only interested the LATEST order of each customer. I'm trying to use SELECT TOP, but somehow it doesn't work with Group function:
    Code:
    SELECT TOP 1 CustomerID,ProductOrdered,OrderQuantity, MAX(OrderDate) from CustomerTable
    group by CustomerID,ProductOrdered,OrderQuantity
    Please advise
    Thanks in advance
  • patjones
    Recognized Expert Contributor
    • Jun 2007
    • 931

    #2
    The TOP 1 feature will only grab the very first record from your table.

    You could try something like this:

    Code:
    SELECT * 
    FROM CustomerTable INNER JOIN (SELECT CustomerID, MAX(OrderDate) AS latest_order_date
                                   FROM CustomerTable
                                   GROUP BY CustomerID) AS tblMax ON (CustomerTable.CustomerID = tblMax.CustomerID AND CustomerTable.OrderDate = tblMax.latest_order_date);

    Pat

    Comment

    • patjones
      Recognized Expert Contributor
      • Jun 2007
      • 931

      #3
      I would also add that you should make sure that CustomerID and OrderDate are indexed columns.

      Pat

      Comment

      • sarah2855
        New Member
        • May 2010
        • 21

        #4
        Originally posted by sarah2855
        I have a table that looks like this:
        CustomerID ProductOrdered OrderDate OrderQuantity
        0001 ProdA 1/1/2007 3
        0001 ProdA 1/1/2008 2
        0002 ProdB 1/1/2006 1


        I'm only interested the LATEST order of each customer. I'm trying to use SELECT TOP, but somehow it doesn't work with Group function:
        Code:
        SELECT TOP 1 CustomerID,ProductOrdered,OrderQuantity, MAX(OrderDate) from CustomerTable
        group by CustomerID,ProductOrdered,OrderQuantity
        Please advise
        Thanks in advance
        @ Pat: thanks Pat, your solution worked perfectly fine. They are not indexed columns but it's a small database. do you think it's gonna be an issue?

        Comment

        • patjones
          Recognized Expert Contributor
          • Jun 2007
          • 931

          #5
          It is generally good practice to do joins on indexed columns, and since it doesn't really take much effort to go into table design view and do it, I would certainly make the change.

          Pat

          Comment

          Working...