We help IT Professionals succeed at work.
Get Started

RANK() or possibly ROW_NUMBER() question

97 Views
Last Modified: 2015-03-01
Assume a table with 5 columns

CREATE TABLE Table1
 
(ID INT IDENTITY(1,1) NOT NULL,
 
COL_A INT,
 
COL_B INT,

COL_C DATETIME2,

COL_D INT)
 
INSERT INTO Table1 (COL_A, COL_B, COL_C, COL_D) VALUES ( -6666, 6666, '2015-02-27 19:00', 1)
INSERT INTO Table1 (COL_A, COL_B, COL_C, COL_D) VALUES ( -7777, 7777, '2015-02-27 20:00', 1)
INSERT INTO Table1 (COL_A, COL_B, COL_C, COL_D) VALUES ( -8888, 8888, '2015-02-27 20:00', 1)

SELECT * FROM Table1


ID      COL_A      COL_B      COL_C                                              COL_D
1      -6666      6666      2015-02-27 19:00:00.0000000      1
2      -7777      7777      2015-02-27 20:00:00.0000000      1
3      -8888      8888      2015-02-27 20:00:00.0000000      1

I need to be able to rank (or row number) these so that the Rank will look like the following:
ID      COL_A      COL_B      COL_C                                             COL_D      RANKED
1      -6666      6666      2015-02-27 19:00:00.0000000      1            1
3      -8888      8888      2015-02-27 20:00:00.0000000      1            1
2      -7777      7777      2015-02-27 20:00:00.0000000      1            2

Notice that COL_C is the same for IDs 2 & 3, but different for ID 1.

All my attempts to rank these correctly fail. How do I do this?

I am using SQL Server 2014, but I think the syntax has been the same for RANK() since SQL Server 2008.
Comment
Watch Question
EE Topic Advisor
CERTIFIED EXPERT
Most Valuable Expert 2014
Awarded 2013
Commented:
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE