我有这样的数据库
ID DATE QTY PRICE
1 05-02-13 00:45 70 0
1 05-02-13 00:45 25 20000
1 05-02-13 00:45 3 1750000
1 05-02-13 00:45 50 0
1 05-02-13 00:45 5 0
1 05-02-13 00:45 200 0
1 05-02-13 00:45 15000 8500
8 11-02-13 16:27 150 17000
8 11-02-13 16:27 150 2000
9 11-02-13 21:40 1 7500000
9 11-02-13 21:40 1 15000000
1 15-02-13 15:15 70 0
1 15-02-13 15:15 25 20000
1 15-02-13 15:15 3 1750000
1 15-02-13 15:15 50 0
1 15-02-13 15:15 5 0
1 15-02-13 15:15 200 0
1 15-02-13 15:15 15000 8500
我需要MySQL中的Query来显示这样的数据:
ID DATE QTY PRICE
8 11-02-13 16:27 150 17000
8 11-02-13 16:27 150 2000
9 11-02-13 21:40 1 7500000
9 11-02-13 21:40 1 15000000
1 15-02-13 15:15 70 0
1 15-02-13 15:15 25 20000
1 15-02-13 15:15 3 1750000
1 15-02-13 15:15 50 0
1 15-02-13 15:15 5 0
1 15-02-13 15:15 200 0
1 15-02-13 15:15 15000 8500
所以我可以提供数量*价格
其唯一的用户最新ID和总和数量*价格
答案 0 :(得分:0)
您应该能够使用子查询为每个max(date)
选择id
,然后将其加入到您的表中以获得结果:
select t1.id,
t1.date,
t1.qty,
t1.price
from yourtable t1
inner join
(
select id, max(date) MaxDate
from yourtable
group by id
) t2
on t1.id = t2.id
and t1.date = t2.maxdate
然后,如果您想sum()
结果,您将使用:
select t1.id,
t1.date,
sum(t1.qty *t1.price) Total
from yourtable t1
inner join
(
select id, max(date) MaxDate
from yourtable
group by id
) t2
on t1.id = t2.id
and t1.date = t2.maxdate
group by t1.id, t1.date