SQL实现分组排序编号(rownumber+over的替代办法)

今天看到论坛有人提问:按规律自动生成序号

要实现的效果如下:


1、建表语句、插入数据:

CREATE TABLE tb(pz NVARCHAR(10),jzyf DATE);

INSERT INTO tb
SELECT '毛笔','2014-05-03' UNION ALL
SELECT '毛笔','2014-12-08' UNION ALL
SELECT '毛笔','2014-07-26' UNION ALL

SELECT '钢笔','2014-08-12' UNION ALL
SELECT '钢笔','2014-12-23' UNION ALL
SELECT '钢笔','2015-02-09' UNION ALL
SELECT '钢笔','2014-10-30' UNION ALL
SELECT '钢笔','2014-11-08' UNION ALL

SELECT '铅笔','2014-04-13' UNION ALL
SELECT '铅笔','2014-05-18' UNION ALL
SELECT '铅笔','2014-08-26' UNION ALL
SELECT '铅笔','2014-10-18' UNION ALL
SELECT '铅笔','2014-12-08'

2、实现代码如下:

SELECT pz,jzyf,NO
FROM 
(
SELECT t.*,
       CASE WHEN @partition_by = t.pz THEN @rownum := @rownum + 1 
            ELSE @rownum :=1
	   END AS NO,
       @partition_by := pz AS partition_by
FROM tb t
INNER JOIN (SELECT @rownum :=0) r
        ON 1=1
INNER JOIN (SELECT @partition_by :='') p
        ON 1=1
ORDER BY t.pz,t.jzyf
)tb

再简化一下:

SELECT pz,jzyf,NO
FROM 
(
SELECT t.*,
       CASE WHEN @partition_by = t.pz THEN @rownum := @rownum + 1 
            ELSE @rownum :=1
	   END AS NO,
       @partition_by := pz AS partition_by
FROM tb t
INNER JOIN (SELECT @rownum :=0,@partition_by :='') r
        ON 1=1
ORDER BY t.pz,t.jzyf
)tb


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值