我在SQL Server中有一个名为table1的表,如下所示:
colA
-------
A123
Z123
C123
B123
现在我想使用一个SQL语句来获得如下结果:
ID colA
--------
1 A123
2 Z123
3 C123
4 B123
colA的顺序是表中行的顺序。不需要对它进行排序。
怎么做? 非常感谢
答案 0 :(得分:8)
这是我在需要递增ID 而不对数据进行排序时总是做的事情(因为我的其他行或行既不是字母也不是按时间顺序排列)。另外,我鄙视使用临时表,除非它们是绝对必要的。
SELECT ROW_NUMBER() OVER
(
ORDER BY (SELECT NULL)
) as ID, colA
FROM table1
答案 1 :(得分:3)
使用ROW_NUMBER的示例
SELECT ROW_NUMBER()
OVER (ORDER BY colA) AS Row,
colA
FROM table1
答案 2 :(得分:2)
使用Table variable with an Identity column
尝试此操作。
colA的顺序是表中行的顺序。不需要 排序。
<强> Fiddle demo: 强>
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 |
答案 3 :(得分:1)
在存在动态订单条件时生成行号
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