如何在同一查询中获取带有行号的 MAX 行号
How to get MAX rownumber with rowNumber in same query
我在 sql 语句中有 ROW_NUMBER() OVER (ORDER BY NULL) rnum
给我行号。有没有办法将最大 rnum 附加到同一个数据集?
我想要的是我得到的 row_number()
,但我还想要每条记录上总 return 的最大行数。
SELECT
ROW_NUMBER() OVER (ORDER BY NULL) rnum,
C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3
FROM SCHEMA.TABLE
WHERE (C.IS_CRNT = 1)
), MAX_NUM as (
SELECT DATA.ID, max(rnum) as maxrnum from DATA GROUP BY DATA.COMPONENT_ID
) select maxrnum, DATA.* from DATA JOIN MAX_NUM on DATA.COMPONENT_ID = MAX_NUM.COMPONENT_ID
期望的结果(假设 15 条记录):
1 15 DATA
2 15 DATA
3 15 DATA
etc...
我想你想要 count(*)
作为 window 函数:
SELECT ROW_NUMBER() OVER (ORDER BY NULL) as rnum,
COUNT(*) OVER () as cnt,
C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3
FROM SCHEMA.TABLE
WHERE C.IS_CRNT = 1
根据我在您的数据集中的假设,我将采用以下方法:
WITH CTE AS (
select C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID)
FROM SCHEMA.TABLE WHERE (C.IS_CRNT = 1))
SELECT *, (select count(*) from cte) "count" from cte;
我在 sql 语句中有 ROW_NUMBER() OVER (ORDER BY NULL) rnum
给我行号。有没有办法将最大 rnum 附加到同一个数据集?
我想要的是我得到的 row_number()
,但我还想要每条记录上总 return 的最大行数。
SELECT
ROW_NUMBER() OVER (ORDER BY NULL) rnum,
C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3
FROM SCHEMA.TABLE
WHERE (C.IS_CRNT = 1)
), MAX_NUM as (
SELECT DATA.ID, max(rnum) as maxrnum from DATA GROUP BY DATA.COMPONENT_ID
) select maxrnum, DATA.* from DATA JOIN MAX_NUM on DATA.COMPONENT_ID = MAX_NUM.COMPONENT_ID
期望的结果(假设 15 条记录):
1 15 DATA
2 15 DATA
3 15 DATA
etc...
我想你想要 count(*)
作为 window 函数:
SELECT ROW_NUMBER() OVER (ORDER BY NULL) as rnum,
COUNT(*) OVER () as cnt,
C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3
FROM SCHEMA.TABLE
WHERE C.IS_CRNT = 1
根据我在您的数据集中的假设,我将采用以下方法:
WITH CTE AS (
select C.ID, C.FIELD1, C."NAME", C.FIELD2, C.FIELD3, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID)
FROM SCHEMA.TABLE WHERE (C.IS_CRNT = 1))
SELECT *, (select count(*) from cte) "count" from cte;