我想在行存在注释时获取增量索引。我试图用ROW_Number()实现相同,但似乎用于生成它的方法存在问题。
SELECT * RowNo,
(SELECT CASE
WHEN LEN(Value) > 0 THEN ROW_NUMBER()
OVER (
ORDER BY ID)
ELSE ''
END
FROM Dictionary
WHERE ID = ABC.ID) Note
FROM ABCD AS ABC WITH(NOLOCK)
INNER JOIN XYZ AS XYZ WITH(NOLOCK)
ON ABC.Id = XYZ.ID
WHERE ABC.Id = 10
预期输出:
ID Name Note
1 A 1
2 B
3 C 2
4 D
5 E
6 F 3
答案 0 :(得分:3)
此处不需要子查询,并且您希望使用partition by
参数将values
与len(value)>0
的{{1}}与没有值的SELECT
ID,
Name,
CASE WHEN LEN(Value)>0 THEN ROW_NUMBER() OVER (
PARTITION BY CASE WHEN LEN(Value)>0 THEN 1 ELSE 0 END
ORDER BY ID) ELSE '' END as Note
FROM ABCD AS ABC WITH(NOLOCK)
INNER JOIN XYZ AS XYZ WITH(NOLOCK)
ON ABC.Id = XYZ.ID
Where ABC.Id = 10
分开:
{{1}}
答案 1 :(得分:2)
我想也许您需要更改方法以使Dictionary查询成为“主要”查询。如果不确切知道你的桌子是什么样的话,很难说。您的预期输出中的“Id”来自哪个表?
试试这样:
WITH cte AS (
SELECT ID, ROW_NUMBER() OVER (ORDER BY ID) AS Note
FROM Dictionary WHERE ID=10
AND LEN(Value)>0
)
SELECT ABC.ID, [Name], cte.Note
FROM ABCD AS ABC WITH(NOLOCK)
INNER JOIN XYZ AS XYZ WITH(NOLOCK) ON ABC.Id = XYZ.ID
LEFT OUTER JOIN cte ON ABC.Id=cte.ID