SQL Server 2008 R2:ROW_NUMBER(),包含2列

时间:2017-09-29 09:37:13

标签: sql sql-server sql-server-2008-r2

表格结构:

CREATE TABLE AZTool
(
    t_ID int,
    z_ID int,
    col_date date
);

插入数据:

INSERT INTO AZTool values(12,23409,'2017-01-02')
INSERT INTO AZTool values(12,23409,'2017-01-03')
INSERT INTO AZTool values(21,23409,'2017-03-14')
INSERT INTO AZTool values(12,24455,'2017-04-22')
INSERT INTO AZTool values(22,24455,'2017-05-13')
INSERT INTO AZTool values(22,35600,'2017-04-04')
INSERT INTO AZTool values(23,35600,'2017-05-14')
INSERT INTO AZTool values(24,35600,'2017-05-16')
INSERT INTO AZTool values(25,35600,'2017-05-24')

预期产出:

t_ID    z_ID    RowNumber
-------------------------
12      23409   1
12      23409   1
21      23409   2
12      24455   1
22      24455   2
22      35600   1
23      35600   2
24      35600   3
25      35600   4

我的尝试:

SELECT
    t_ID, z_ID,
    ROW_NUMBER() OVER (PARTITION BY t_ID, z_ID ORDER BY z_ID) rn
FROM 
    AZTool

2 个答案:

答案 0 :(得分:3)

我纠正的问题:

  • 从分区中删除 scheme : [http, https, ftp, file] domain : [www.stackoverflow.com, localhost, ipAddress] path : [/questions/26663573/, /Users/youUserName/subDirName] scheme | domain | path file://localhost/Users/youruserName/file.txt
  • t_ID条款
  • 中按t_ID排序
  • 使用ORDER BY代替DENSE_RANK


ROW_NUMBER

答案 1 :(得分:1)

使用DENSE_RANK()功能:

SELECT t_ID,z_ID,DENSE_RANK() OVER(PARTITION BY z_ID ORDER BY t_ID) rn
FROM AZTool

结果:

enter image description here