按mysql工作批中的限制记录分组

时间:2016-06-10 11:10:22

标签: mysql sql database mysql-workbench mysqldump

我使用的是mysql wokrbatch。我需要2个记录的结果组明智限制。 我有如下表:

|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|

我希望得到以下结果:

|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|

结果基于按名称降序排列并且只有 前2条记录

我使用了以下查询

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;

但它按名称给出了所有的分组结果 记录我只需要两个最佳记录。

2 个答案:

答案 0 :(得分:0)

您可以使用相关子查询执行分组限制,但不能使用count()而不能使用group by。这是一种方式:

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;

答案 1 :(得分:0)

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;

根据您最后2条评论,您可以获得请求1和2但不能获得3,因为如果您想要= 2并且按p_date分组,则无法获得3(请参阅样本)

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;