name amount date
x 200 2016-08-11 07:00:00
x 111 2016-08-03 19:32:34
y 10 2016-07-19 07:00:00
y 9 2016-07-20 09:30:00
我想为每个用户获得最后一天的付费金额,我想要这样的输出
name amount date
x 200 2016-08-11 07:00:00
y 9 2016-07-20 09:30:00
如何查找每个用户的最后更新数据组
答案 0 :(得分:1)
只需尝试这个
$sql = "SELECT * FROM table_name ORDER BY `date` DESC GROUP BY `name`";
$query = $this->db->query($sql);
$result = $query->result_array();
print_r($result);
答案 1 :(得分:0)
使用MAX我们可以实现这个目标
DECLARE @Table1 TABLE
( name varchar(1), amount int, date varchar(19))
;
INSERT INTO @Table1
( name , amount , date )
VALUES
('x', 200, '2016-08-11 07:00:00'),
('x', 111, '2016-08-03 19:32:34'),
('y', 10, '2016-07-19 07:00:00'),
('y', 9, '2016-07-20 09:30:00')
;
脚本
select T.name , T.amount,TT.Dt as Dates from @Table1 T
INNER JOIN (select name,MAX(date)Dt from @Table1
GROUP BY Name)TT
ON T.name = TT.name AND T.date = TT.Dt
ORDER BY T.name