Add row number to this T-SQL query

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

  • Hashbytes Computed column cannot be persisted because the column is non-deterministic
  • Is there a 'START AT' equivalent in MS-SQL?
  • Load CSV by matching table column to SQL using PowerShell
  • Create a view with ORDER BY clause
  • Best login practice
  • Database-wide unique-yet-simple identifiers in SQL Server
  • 2 Solutions collect form web for “Add row number to this T-SQL query”

    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
    

    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
    
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.