1. 程式人生 > >SQL實現分組排序編號(rownumber+over的替代辦法)

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