存储过程实现开窗函数功能

BEGIN  
      -- Created by ytt at 2014/1/10  
      -- Do a row_number() over()   
      DECLARE i INT;  
      -- Create a temporary table to save result.  
      DROP TABLE IF EXISTS tmp_rownum;  
      SET @stmt = CONCAT('create temporary table tmp_rownum select *,''rownum'' from ',f_table_name,' where 1 = 0');  
      PREPARE s1 FROM @stmt;  
      EXECUTE s1;  
        
    
      SET i = 0;  
      SET @j = 0;  
      SET @v_column_paritionby = '';  
  
  
      -- Check whether  parition column is null or not.  
      IF (f_column_partitionby = '' OR f_column_partitionby IS NULL) THEN   
         -- No additional parition column.  
    SET @stmt = CONCAT('insert into tmp_rownum select *,@j:= @j+1 as rownum from ',  
            f_table_name);      
    PREPARE s1 FROM @stmt;  
    EXECUTE s1;   
      ELSE  
       -- Give partition column.  
    SET @stmt = CONCAT('select count(*) from (select count(*) from ',f_table_name,' group by ',  
            f_column_partitionby,') as a into @cnt');  
    PREPARE s1 FROM @stmt;  
    EXECUTE s1;  
        
        WHILE i < @cnt  
        DO          
      -- Get the partition value one by one.  
      SET @stmt = CONCAT('select ',f_column_partitionby,' from ',f_table_name,' group by  ',f_column_partitionby,' limit ',i,',1 into @v_column_partitionby');  
      PREPARE s1 FROM @stmt;   
      EXECUTE s1;  
      -- Check whether sort is needed.  
          IF f_column_orderby = '' OR f_column_orderby IS NULL THEN  
            SET @stmt = CONCAT('insert into tmp_rownum select *,@j:= @j+1 as rownum from ',  
            f_table_name,' where ',f_column_partitionby,' = ''',@v_column_partitionby,'''');  
      ELSE   
        SET @stmt = CONCAT('insert into tmp_rownum select *,@j:= @j+1 as rownum from ',  
            f_table_name,' where ',f_column_partitionby,' = ''',@v_column_partitionby,'''  
            order by ',f_column_orderby,' ',f_is_asc);  
          END IF;  
          SET @j = 0;  
      PREPARE s1 FROM @stmt;  
      EXECUTE s1;   
      
          SET i = i + 1;  
        END WHILE;  
      END IF;  
      -- Reset all session variables.  
      SET @j = NULL;  
      SET @v_column_paritionby = NULL;  
      SET @cnt = NULL;  
      SELECT * FROM tmp_rownum;  
    END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值