gesanri :
I have an table like this:
CREATE TABLE `test` (
`id` int NOT NULL AUTO_INCREMENT ,
`sale_date` date NOT NULL ,
`store_id` varchar(64) NOT NULL ,
`money` decimal(10,2) NOT NULL ,
`type` tinyint(4) NOT NULL ,
PRIMARY KEY (`id`)
);
and I insert the data as below:
2020-03-12 111 500 1
2020-03-12 111 800 2
2020-03-12 222 900 2
I want to group by sale_date and store_id,and inner group order by type desc, my sql is like this:
select * from(
select * from test order by type desc) r group by sale_date, store_id;
but the result is:
2020-03-12 111 500 1
2020-03-12 222 900 2
and the result is supposed to be like this:
2020-03-12 111 800 2
2020-03-12 222 900 2
forpas :
Use a correlated subquery:
select t.*
from test t
where t.type = (select max(type) from test where sale_date = t.sale_date and store_id = t.store_id)
See the demo.
Results:
| id | sale_date | store_id | money | type |
| --- | ---------- | -------- | ----- | ---- |
| 2 | 2020-03-12 | 111 | 800 | 2 |
| 3 | 2020-03-12 | 222 | 900 | 2 |
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=217415&siteId=1