使用其他列的组选择最大日期

时间:2012-11-01 04:52:05

标签: mysql count group-by

我有一张表:

gold_2012

gold_city | gold_type | gold_cost | gold_selltime
--------------------------------------------------
city1     | type 1    | 41.23     | 2012-01-01   
city1     | type 1    | 42.23     | 2012-02-02   
city1     | type 1    | 40.23     | 2012-03-03   
city2     | type 2    | 43.23     | 2012-01-01   
city2     | type 2    | 45.23     | 2012-02-02   
city2     | type 2    | 47.23     | 2012-03-03   
city3     | type 3    | 48.23     | 2012-01-01   
city3     | type 3    | 49.23     | 2012-02-02   
city3     | type 3    | 44.23     | 2012-03-03   

如何通过gold_selltimegold_city gold_type desc为每个组获取最后一个结果排序。

我用过这个:

SELECT * , COUNT( * ) 
FROM  gold_2012
GROUP BY  gold_type ,  gold_city
ORDER BY gold_selltime DESC

但它不起作用。
我的结果只有:

gold_city | gold_type | gold_cost | gold_selltime
--------------------------------------------------
city1     | type 1    | 41.23     | 2012-01-01   
city2     | type 2    | 43.23     | 2012-01-01   
city3     | type 3    | 48.23     | 2012-01-01   

但我需要它:

gold_city | gold_type | gold_cost | gold_selltime
--------------------------------------------------
city1     | type 1    | 40.23     | 2012-03-03   
city2     | type 2    | 47.23     | 2012-03-03   
city3     | type 3    | 44.23     | 2012-03-03   

抱歉!我忘记了!请参阅上面我编辑的问题。

2 个答案:

答案 0 :(得分:12)

您可以使用MAX功能:

SELECT gold_city, gold_type 
       , MAX(gold_selltime) AS gold_selltime, COUNT( * ) AS `COUNT`
FROM gold_2012 
GROUP BY gold_type , gold_city 
ORDER BY gold_selltime DESC

See this SQLFiddle

注意:您可以使用DATE_FORMAT功能转换日期:

DATE_FORMAT(MAX(gold_selltime), '%Y-%m-%d') AS gold_selltime

See this SQLFiddle

更新

由于OP改变了他/她的要求,请看这个更新的答案:

您可以使用以下查询来实现:

SELECT *
FROM gold_2012
WHERE gold_selltime IN
(
    SELECT MAX(gold_selltime) AS gold_selltime
    FROM gold_2012  
)

See this SQLFiddle

答案 1 :(得分:0)

试试这个

SELECT gold_city,gold_type , MAX(gold_selltime)
FROM gold
WHERE gold_city IN (select distinct gold_city from gold) 
GROUP BY gold_city ,gold_type