如何在SQL Server中为行分区设置分区ID /名称?

时间:2016-01-06 17:27:31

标签: sql sql-server select row

如何在SQL Server中为行分区设置分区ID /名称?

name surname val
a  b      10
c  d      2
a  b      11
a  b      13

结果(按名称和姓氏划分):

 name surname val rowno partitionid

 a    b        10   1    1
 a    b        11   2    1
 a    b        13   3    1
 c    d        2    1    2

2 个答案:

答案 0 :(得分:4)

DECLARE @table TABLE( name CHAR(1) , surname CHAR(1) , val TINYINT )

INSERT INTO @table
VALUES ( 'a' , 'b' , 10 ) 
, ( 'c' , 'd' , 2 )
, ('a' , 'b' , 11 )
, ( 'a' , 'b' , 13 )

SELECT * FROM @table

SELECT *
, ROW_NUMBER() OVER ( PARTITION BY name, surname ORDER BY val ) as rowno
, DENSE_RANK() OVER ( ORDER BY name ) as partitionid
FROM @table

问候!

答案 1 :(得分:3)

dense_rank窗口函数似乎符合要求:

SELECT *,
       DENSE_RANK() OVER (PARTITION BY name, surname ORDER BY val) AS rowno,
       DENSE_RANK() OVER (ORDER BY name, surname) AS partitionid
FROM   mytable