简体   繁体   中英

SQL Server 2008 R2: ROW_NUMBER() with 2 columns

Table structure:

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

Insert data:

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')

Expected output:

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

My attempt:

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

Problems I corrected:

  • Remove t_ID from the partition
  • Order by t_ID in the ORDER BY clause
  • Use DENSE_RANK instead of ROW_NUMBER


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

Use DENSE_RANK() Function :

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

Result :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM