0

我有这样的数据库

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

所以我可以求和 QTY * PRICE

它唯一的用户最新 ID 和总和数量 * 价格

4

1 回答 1

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

请参阅SQL Fiddle with Demo

然后,如果您想要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

请参阅带有演示的 SQL Fiddle

于 2013-02-24T18:40:04.753 回答