Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add row number to this T-SQL query

Tags:

sql

sql-server

How can I add ROW numbers to this query result?

SELECT DISTINCT
  VehicleSpecs.SubmittedById,
  COUNT(VehicleSpecs.SubmittedById) AS NumCars,
  aspnet_Users.UserName
FROM
  VehicleSpecs
  INNER JOIN aspnet_Users ON VehicleSpecs.SubmittedById = aspnet_Users.UserId
WHERE
  (LEN(VehicleSpecs.SubmittedById) > 0)
GROUP BY
  VehicleSpecs.SubmittedById,
  aspnet_Users.UserName
ORDER BY
  NumCars DESC
like image 418
Mario Avatar asked Feb 05 '12 15:02

Mario


People also ask

How can add row number in SQL Server query?

To add a row number column in front of each row, add a column with the ROW_NUMBER function, in this case named Row# . You must move the ORDER BY clause up to the OVER clause. SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.

How do I number a row in SQL?

If you'd like to number each row in a result set, SQL provides the ROW_NUMBER() function. This function is used in a SELECT clause with other columns. After the ROW_NUMBER() clause, we call the OVER() function. If you pass in any arguments to OVER , the numbering of rows will not be sorted according to any column.

What is ROW_NUMBER () function in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

How do I add a number to a SQL query?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.


2 Answers

Add: ROW_NUMBER() OVER (ORDER BY NumCars)

EDIT:

WITH    t1 AS 
( SELECT DISTINCT
            VehicleSpecs.SubmittedById ,
            COUNT(VehicleSpecs.SubmittedById) AS NumCars ,
            aspnet_Users.UserName
   FROM     VehicleSpecs
            INNER JOIN aspnet_Users ON VehicleSpecs.SubmittedById = aspnet_Users.UserId
   WHERE    ( LEN(VehicleSpecs.SubmittedById) > 0 )
   GROUP BY VehicleSpecs.SubmittedById ,
            aspnet_Users.UserName
)
SELECT  ROW_NUMBER() OVER ( ORDER BY NumCars ), *
FROM    t1
ORDER BY NumCars
like image 127
Tomek Avatar answered Sep 26 '22 00:09

Tomek


Wrap you entire query in a sub query and add row_number in the outer query.

select *, row_number() over(order by (select 0)) as rn
from
  (
    select distinct -- your columns
    from YourTable
  ) as T
order by NumCars desc
like image 26
Mikael Eriksson Avatar answered Sep 26 '22 00:09

Mikael Eriksson