简体   繁体   中英

Group by limit records in mysql workbatch

i am use a mysql wokrbatch. i need result group wise limit of 2 records. i have table like below:

|P_ID |Name     |Price | p_date             |
|1    |T-shirt  |500   | 2016-06-10 10:10:25|
|2    |T-shirt  |410   | 2016-06-10 10:10:27|
|3    |shirt    |450   | 2016-06-10 10:10:30|
|4    |T-shirt  |300   | 2016-06-10 10:10:30|
|5    |shirt    |500   | 2016-06-10 10:10:25|
|6    |pent     |600   | 2016-06-10 10:10:10|

and i want following result:

|Name     |Price | p_date             |
|shirt    |450   | 2016-06-10 10:10:30|
|shirt    |500   | 2016-06-10 10:10:25|
|T-shirt  |300   | 2016-06-10 10:10:30|
|T-shirt  |410   | 2016-06-10 10:10:27|

the result is base on group by name with descending order and have only top 2 records

i have use the following query

select 
    name, price, p_date
from
    tempData.item_Master
where
    name in (select 
            name
        from
            tempData.item_Master
        group by name
        having count(name) > 1)
group by name , p_date
order by name , p_date DESC;

but it gives group by name result with all records i need only two top records.

You can do a group-wise limit with a correlated subquery, but not with count() and not with group by . Here is one way:

select im.name, im.price, im.p_date
from tempData.item_Master im
where (select count(*)
       from tempData.item_Master im2
       where im2.name = im.name and
             im2.p_id <= im.p_id
      ) <= 2
order by name, p_date DESC;
select  name, price, p_date
from   tempData.item_Master
where  name in 
 (select  name
  from   tempData.item_Master
    group by name
    having count(*) > 1)
order by name , p_date DESC;

and based on you last 2 comment you can obtain the request 1 and 2 but not the 3 because if you want having = 2 and group by p_date you can't get the 3 (see you sample)

select  name, price, p_date
from   tempData.item_Master
where  name in 
 (select  name
  from   tempData.item_Master
    group by name, p_date
    having count(*) = 2)
order by name , p_date DESC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM