例如,我有这样的表:
Date | Id | Total
-----------------------
2014-01-08 1 15
2014-01-09 3 24
2014-02-04 3 24
2014-03-15 1 15
2015-01-03 1 20
2015-02-24 2 10
2015-03-02 2 16
2015-03-03 5 28
2015-03-09 5 28
我希望输出为:
Date | Id | Total
---------------------
2015-01-03 1 20
2014-02-04 3 24
2015-03-02 2 16
2015-03-09 5 28
这里的不同值是Id。我需要每个Id的最新总计。
答案 0 :(得分:2)
您可以将left join
用作
select
t1.* from table_name t1
left join table_name t2
on t1.Id = t2.Id and t1.Date >t2.Date
where t2.Id is null
http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
答案 1 :(得分:0)
你也可以在sql中使用Max():
SELECT date, id, total
FROM table as a WHERE date = (SELECT MAX(date)
FROM table as b
WHERE a.id = b.id
)
答案 2 :(得分:0)
您可以按照以下方式执行此操作
SELECT *
FROM YourTable D
WHERE date = (SELECT MAX(date) FROM YourTable WHERE ID = D.ID)
答案 3 :(得分:0)
另一种方法是使用INNER JOIN
根据latest
查找ID
日期,然后将结果重新加入表格以获取value
select A.ID,A.Date,A.value
from yourtable A
INNER JOIN
(
select MAX(date) as Date,ID
from yourtable
group by ID
) B
ON A.ID =B.ID and A.Date = B.Date
答案 4 :(得分:-2)
其他答案对我没用。我找到了以下代码,这对我很有用:
SELECT * FROM TABLE WHERE DATE IN (SELECT MAX(DATE) FROM TABLE)
我正在使用SSMS 2014,SQLServer