7

我在 SQL Server 中有一个名为 table1 的表,如下所示:

colA
-------
A123
Z123
C123
B123

现在我想用一条 SQL 语句来得到结果如下:

ID colA
--------
1  A123
2  Z123
3  C123
4  B123

colA 的顺序与表中的行顺序相同。不需要对其进行排序。

怎么做??非常感谢

4

4 回答 4

21

当我需要一个递增的 ID而不对数据进行排序时,我总是这样做(因为我的另一行或多行既不是按字母顺序排列也不是按时间顺序排列的)。此外,我鄙视使用临时表,除非它们是绝对必要的。

SELECT ROW_NUMBER() OVER 
(
    ORDER BY (SELECT NULL)
) as ID, colA
FROM table1
于 2014-06-03T18:48:00.037 回答
7

使用 ROW_NUMBER 的示例

             SELECT ROW_NUMBER() 
                OVER (ORDER BY colA)  AS Row, 
                colA
                FROM table1
于 2013-10-18T15:14:01.343 回答
5

尝试使用Table variable with an Identity column.

colA 的顺序与表中的行顺序相同。不需要对其进行排序。

小提琴演示:

declare @t table(id int identity(1,1), colA varchar(50))

--No ordering done and the same results won't be guaranteed
insert into @t select colA from Table1

select id, colA from @T

结果:

| ID | COLA |
|----|------|
|  1 | A123 |
|  2 | Z123 |
|  3 | C123 |
|  4 | B123 |
于 2013-10-18T15:25:52.157 回答
2

Generating Row number when dynamic order conditions are present

select TotalCount = COUNT(U.UnitID) OVER() ,

ROW_NUMBER() over(
    order by 
     (CASE @OrderBy WHEN '1' THEN m.Title  END) ASC ,
     (CASE @OrderBy WHEN '2' THEN m.Title  END) DESC,
     (CASE @OrderBy WHEN '3' THEN Stock.Stock  END) DESC,
     (CASE @OrderBy WHEN '4' THEN Stock.Stock   END) DESC

) as RowNumber,

M.Title,U.ColorCode,U.ColorName,U.UnitID, ISNULL(Stock.Stock,0) as Stock

 from tblBuyOnlineMaster M

    inner join BuyOnlineProductUnitIn U on U.BuyOnlineID=M.BuyOnlineID 

    left join 
            ( select IT.BuyOnlineID,IT.UnitID,ISNULL(sum(IT.UnitIn),0)-ISNULL(sum(IT.UnitOut),0) as Stock 
                from [dbo].[BuyOnlineItemTransaction] IT 
                group by IT.BuyOnlineID,IT.UnitID
             ) as Stock

        on U.UnitID=Stock.UnitID


order by 
 (CASE @OrderBy WHEN '1' THEN m.Title  END) ASC ,
 (CASE @OrderBy WHEN '2' THEN m.Title  END) DESC,
 (CASE @OrderBy WHEN '3' THEN Stock.Stock  END) DESC,
 (CASE @OrderBy WHEN '4' THEN Stock.Stock   END) DESC


offset  @offsetCount rows fetch next 6 rows only 
于 2016-08-18T06:13:00.973 回答