使用联接限制每个组的SQL行

时间:2015-04-09 18:59:03

标签: mysql sql

我试图限制每组输出的行数。这是怎么做的。解释下面的案例:

表1:Customer_Details

Customer ID Vandeur pid_01 Vandeur pid_02 Vandeur pid_03 Vandeur pid_04 Vandeur pid_01 Vandeur pid_02 Vandeur pid_03 Vandeur pid_04 Vandeur pid_05

表2:Month_Details

Month ID Jan pid_01 Jan pid_02 Jan pid_03 Jan pid_04 Feb pid_01 Feb pid_02 Feb pid_03 Feb pid_04 Feb pid_05

我的输出要求是 - 我只希望customer Vandeur每个月的前3个ID

样本O / P:

Customer Month ID Vandeur Jan pid_01 Vandeur Jan pid_02 Vandeur Jan pid_03 Vandeur Feb pid_01 Vandeur Feb pid_02 Vandeur Feb pid_03

有人可以建议我实现它的方法。

1 个答案:

答案 0 :(得分:2)

Mysql不像其他RDBMS那样支持窗口函数,每组可获得n个结果,可以使用用户定义的变量

 SELECT DISTINCT c.Customer,m1.`Month`,c.ID
 FROM Customer_Details c
 JOIN (
  SELECT m.*,
   @r:= CASE WHEN @g = `Month` THEN  @r +1 ELSE 1 END  rank,
   @g:=`Month`
    FROM `Month_Details` m ,
    (SELECT @g:=NULL,@r:=NULL) r   
    ORDER BY m.`Month` DESC ,REPLACE(m.ID,'pid_','') * 1  
     ) m1 ON(c.ID = m1.ID)
  WHERE m1.rank <=3
 AND c.Customer= 'Vandeur'
 ORDER BY m1.`Month` DESC ,REPLACE(m1.ID,'pid_','') * 1

DEMO