I have a table like:
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
How can I get 1 last result order by gold_selltime
desc each group by gold_city
and gold_type
.
I used this:
SELECT * , COUNT( * )
FROM gold_2012
GROUP BY gold_type , gold_city
ORDER BY gold_selltime DESC
but it didn't work.
I only have result like:
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
but I need it like:
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
Sorry! I forget sth! Please see my edited question above.
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
The GROUP BY Clause SQL is used to group rows with same values. The GROUP BY Clause is used together with the SQL SELECT statement. The SELECT statement used in the GROUP BY clause can only be used contain column names, aggregate functions, constants and expressions.
MAX function works with “date” data types as well and it will return the maximum or the latest date from the table.
The GROUP BY clause is used along with some aggregate functions to group columns with the same values in different rows. The group by multiple columns technique retrieves grouped column values from one or more database tables by considering more than one column as grouping criteria.
You can use MAX
function for that:
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
Note: You can convert your date using DATE_FORMAT
function:
DATE_FORMAT(MAX(gold_selltime), '%Y-%m-%d') AS gold_selltime
As OP changed his/her requirement see this updated answer:
You can achieve that using the following query:
SELECT *
FROM gold_2012
WHERE gold_selltime IN
(
SELECT MAX(gold_selltime) AS gold_selltime
FROM gold_2012
)
Try this
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With