我想从我的选择数据中获取记录号。
目前我知道这样的事情:
SELECT max(ROW_NUMBER() OVER(ORDER BY aUniqueField)) FROM aTable
但是这假设aUniqueField是一个唯一的字段,而且它是我返回它的顺序。不幸的是,对我来说情况并非如此。我需要一种方法来贴上'行号,与select语句中的任何字段的值无关。
有办法做到这一点吗?
这是我的两张桌子:
这是我的SQL:
SELECT
FeatureName,
GF.[Enabled] AS [Enabled],
GroupId
FROM
Feature F
JOIN GroupFeature GF ON GF.FeatureId = F.FeatureId
WHERE
GroupId = 1
OR
GroupId = 4
OR
GroupId = 2
Order By
Case GroupId
When 1 Then 1
When 4 Then 2
When 2 Then 3
受欢迎的请求:)我附上更多信息。我真的应该从一开始就这样做。
数据输出:
Feature1, true, 1
Feature2, true, 4
Feature3, true, 4
Feature4, true, 4
Feature5, true, 2
我想要的是:
1,Feature1, true, 1
2,Feature2, true, 4
3,Feature3, true, 4
4,Feature4, true, 4
5,Feature5, true, 2
我发现如果我删除了Order By / When子句,那么在这里使用很多建议就行了。当我恢复它时,我得到这样的东西:
1,Feature1, true, 1
3,Feature2, true, 4
4,Feature3, true, 4
5,Feature4, true, 4
2,Feature5, true, 2
答案 0 :(得分:2)
窗口函数中的ORDER BY
不一定是唯一的,如果不是,您仍会为每一行获得唯一的ROW_NUMBER()
:
DECLARE @t TABLE (id int)
INSERT INTO @t
VALUES
(1)
,(1)
,(1)
,(1)
SELECT ROW_NUMBER() OVER (ORDER BY id), id
FROM @t
返回:
1 1
2 1
3 1
4 1
答案 1 :(得分:2)
我不完全清楚你在寻找什么 添加与任何字段的值无关的行号是奇数,并且您有正确的答案,表明您的工作无效
DECLARE @map table(mapIn int primary key, mapout int)
insert into @map values (1,1), (4,2), (2,3)
select * from @map
SELECT FeatureName, GF.[Enabled] AS [Enabled], GroupId,
ROW_NUMBER() OVER(ORDER BY map.mapout, GF.GroupFeatureID) RowNum
FROM Feature F
JOIN GroupFeature GF
ON GF.FeatureId = F.FeatureId
join @map map
on map.mapIn = GF.GroupId
order by map.mapout, GF.GroupFeatureID
答案 2 :(得分:0)
您可以使用
ROW_NUMBER() over (order by (Select 1))
获取独立的行号
答案 3 :(得分:0)
您可以使用NewID()获取行号而无需重新排序数据:
SELECT max(ROW_NUMBER() OVER(ORDER BY NewID())) FROM aTable