cantaffordavan
cantaffordavan

Reputation: 1447

Group by and display latest entry date for that group

I have a groupby and sum table that I use to display current stock (it groups and sums all stock entries). I want to now display the latest entry date for each groupby group.

Here is what I'm working with:

-------------------------------------------------------------------
ProductID   |  Color  | Timestamp          |  Quantity  |  RowID  |
-------------------------------------------------------------------
25          |  Red    | 10/10/10 06:22:15  |  250       |  1      |
-------------------------------------------------------------------
32          |  Green  | 10/10/10 06:23:45  |  100       |  2      |
-------------------------------------------------------------------

$query = "SELECT productid, color, SUM(Quantity) AS TotalQuantity FROM inventory GROUP BY productid, color";
$result = mysql_query($query) or die(mysql_error());

   // Table markup here
   echo '<tr><td>'. $row['productid'] . '</td><td>' . $row['color']. '</td><td>'. $row['TotalQuantity'];
   // Table markup here

I was trying to use the max value function to get the max rowid for each groupby but it was getting so confusing!

Upvotes: 0

Views: 94

Answers (1)

Olivier Coilland
Olivier Coilland

Reputation: 3096

Well, if the latest entry date for each group is also by construction the most recent one, you can simply use:

SELECT
    productid,
    color,
    SUM(Quantity) AS TotalQuantity,
    MAX(Timestamp) AS LatestDate
FROM inventory
GROUP BY productid, color;

Upvotes: 3

Related Questions