查询组,购买给出最新的ID不是最新的

时间:2015-03-09 14:34:33

标签: mysql

我有一个MYSQL数据库,我正在运行一个返回一组记录的查询,按UNIT_ID分组。

原始数据:

ID, UNIT_ID, BILL_TYPE, ADDED_ON
 3, 1130,     1,       '2014-01-01'
 4, 1130,     1,       '2014-02-01'
 5, 1130,     1,       '2014-03-01'
 6, 1234,     1,       '2014-01-02'
 7, 1234,     1,       '2014-02-02' 

如果我运行当前查询:

select * 
  from bills 
 where bill_type = 1 
 group 
    by unit_id 
 order 
    by unit_id
     , added_on desc;

......我明白了:

3, 1130, 1, '2014-01-01'
6, 1234, 1, '2014-01-02'

..但我想:

5, 1130, 1, '2014-03-01'
7, 1234, 1, '2014-02-02'

基本上,我想要最新的条目(每个UNIT_ID最高的ADDED_ON,而不是最旧的。我怎么能得到这个?

谢谢,鲍勃

2 个答案:

答案 0 :(得分:1)

SELECT DISTINCT bills.id, bills.unit_id, bills.added_on
FROM bills 
INNER JOIN (
SELECT unit_id, MAX(added_on) as added_on
FROM bills
GROUP BY unit_id 
) AS b
ON bills.unit_id = b.unit_id
  AND bills.added_on = b.added_on
WHERE bills.bill_type = 1 

答案 1 :(得分:1)

您可以使用以下技术

来完成
select b.* from bills b
left join bills b1 
on b1.UNIT_ID = b.UNIT_ID
and b1.ID > b.ID
where 
b.BILL_TYPE = 1 
and b1.id is null

http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html