我有一张这样的表:
.--------------------------------.
| Name | XX | Date |
.--------------------------------.
| N1 | 5 | 2009-05-01 |
| N1 | 10 | 2008-01-08 |
| N2 | 8 | 2009-02-02 |
.________________________________.
我的结果应该是这样的:
.------------.
| Name | XX |
.------------.
| N1 | 5 |
| N2 | 8 |
.____________.
我只想要按名称分组的行,但只需要最新的行。我不希望在这个例子中XX = 10的行因为日期2009-05-01> 2008-01-08
我不知道如何按日期排序并将其分组:(
答案 0 :(得分:2)
您想要分组的内容是什么?
select Name, XX
from yourTable t1
where Date = (select MAX(Date)
from yourTable t2
where t1.Name = t2.Name)
如果您需要在最后一天汇总XX,那么:
select Name, SUM(XX)
from yourTable t1
where Date = (select MAX(Date)
from yourTable t2
where t1.Name = t2.Name)
group by Name
答案 1 :(得分:0)
SELECT Name, XX FROM myTable GROUP BY Name ORDER BY Date DESC
您可能需要在日期字段周围加上引号
`Date`
答案 2 :(得分:0)
很抱歉,但这两个都错了。
你应该
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