views:

269

answers:

3

I have a table like this:

.--------------------------------.
| Name  | XX | Date              |
.--------------------------------.
| N1    | 5  | 2009-05-01        |
| N1    | 10 | 2008-01-08        |
| N2    | 8  | 2009-02-02        |
.________________________________.

My result should be this:

.------------.
| Name  | XX |
.------------.
| N1    | 5  |
| N2    | 8  |
.____________.

I just want the rows, grouped by Name but just the newest ones. I dont want the row with XX=10 in this example because the date 2009-05-01 > 2008-01-08.

I don't know how to sort by Date and group it :(

A: 
SELECT Name, XX FROM myTable GROUP BY Name ORDER BY Date DESC

You may need to put quotes around your date field

`Date`
Justin Giboney
Sorry, It doesn't work this was :(
Fu86
+2  A: 

What do you want the grouping for?

select Name, XX
  from yourTable t1
 where Date = (select MAX(Date)
                 from yourTable t2
                where t1.Name = t2.Name)

If you need to sum XX for the last day, then:

select Name, SUM(XX)
  from yourTable t1
 where Date = (select MAX(Date)
                 from yourTable t2
                where t1.Name = t2.Name)
 group by Name
Hosam Aly
grouping, because then you don't need a subquery
Justin Giboney
@Justin: Grouping (like in your answer) is using a bad "feature" of MySQL, and it is not ANSI nor ISO compliant. MySQL chooses the first record for fields not mentioned in the `group by` clause, even though this is invalid according to SQL standards.
Hosam Aly
Great, this works perfect, thanks!
Fu86
@Hosam Aly: That makes sense, thanks for teaching me
Justin Giboney
A: 

Sorry but these 2 are both wrong.

You should

SELECT Name, XX
 FROM t1
 JOIN (SELECT Name, max(date)
        FROM t1
        GROUP BY Name) subquery
   ON t1.Name = subquery.Name AND t1.Date = subquery.Date

Saggi Malachi
@Justin your query can not even run since you must have some aggregation function over XX or have it in the GROUP BY clause
Saggi Malachi
@fizz: *"MySQL extends the use of GROUP BY to allow selecting fields that are not mentioned in the GROUP BY clause."* (http://dev.mysql.com/doc/refman/5.0/en/select.html) This is invalid according to SQL standards, but MySQL allows it.
Hosam Aly
oh, I see. thanks. weird feature
Saggi Malachi