我有一组结果,例如发票。
他们想要一组结果,列出每个发票中的项目,但每个结果旁边都有一个行号。
我目前所拥有的(已修改为适合问题);
SELECT
[jvi].[name] AS [ScheduledCode],
[jvi].[description] AS [Description],
[clientReference] AS [TracksheetRef],
(SELECT TOP 1 COUNT(*) FROM [table2items] [jvi1] WHERE [jvi1].[SheetId] = [jvs].[id]) AS [Line],
(SELECT TOP 1 SUM(CAST(([jvi1].[Cost] * [jvi1].[qty]) AS MONEY)) FROM [table2items] [jvi1] WHERE [jvi1].[valuationSheetId] = [jvs].[id]) AS [UpliftedValue],
FROM
[dbo].[table1invoice] [jvs]
INNER JOIN
[dbo].[table2items] [jvi] ON [jvi].[SheetId] = [jvs].[id]
ScheduledCode Description Ref Lines UpliftedValue
C142011 RepairMain/90-150mm/Unmade 0227-0318 1 303.68
C182912 Surfaced 4237-0518 1 211.58
C182912 Install 4626-0518 2 356.24
C182811 Investigation / Unmade 4626-0518 2 356.24
C182811 Poor Supply 3460-0118 2 356.24
如您所见,它计算每张纸有多少行,但我需要在每张纸旁边添加一个数字并向上计数,例如:
1 C182811 Investigation / Unmade 4626-0118 2 356.24
2 C182811 Poor Supply 3460-0118 2 356.24
1 C182912 Surfaced 4237-0518 1 211.58
2 C182912 Install 4626-0518 2 356.24
答案 0 :(得分:1)
只需使用:
row_number() over
(partition by ScheduledCode order by ScheduledCode, UpliftedValue, Description) as rowNum
作为查询的最左列,如下所示:
SELECT row_number() over
(partition by q.ScheduledCode order by q.ScheduledCode, q.UpliftedValue,q.Description ) as rowNum,
q.*
FROM
(
SELECT
[jvi].[name] AS [ScheduledCode],
[jvi].[description] AS [Description],
[clientReference] AS [TracksheetRef],
(SELECT TOP 1 COUNT(*) FROM [table2items] [jvi1] WHERE [jvi1].[SheetId] = [jvs].[id]) AS [Line],
(SELECT TOP 1 SUM(CAST(([jvi1].[Cost] * [jvi1].[qty]) AS MONEY)) FROM [table2items] [jvi1] WHERE [jvi1].[valuationSheetId] = [jvs].[id]) AS [UpliftedValue],
FROM
[dbo].[table1invoice] [jvs]
INNER JOIN
[dbo].[table2items] [jvi] ON [jvi].[SheetId] = [jvs].[id]
) q