6

我有一张像这样的桌子:

金_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_selltimedesc 每组 bygold_city和获得 1 个最后结果顺序gold_type

我用这个:

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   

对不起!我忘记了……!请参阅上面我编辑的问题。

4

2 回答 2

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

看到这个 SQLFiddle

注意:您可以使用DATE_FORMAT以下函数转换日期:

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

看到这个 SQLFiddle

更新

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

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

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

看到这个 SQLFiddle

于 2012-11-01T04:54:06.393 回答
1

试试这个

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
于 2012-11-01T05:15:28.733 回答