Setup
go
create table eidmadm.PerfData1 (id int primary key, c1 varchar(100))
create table eidmadm.PerfData2 (id int identity primary key, fkId int, c1 varchar(100), FOREIGN KEY (fkId) REFERENCES eidmadm.PerfData1(id))
go
DECLARE @id INTEGER = 0;
begin
WHILE @id <= 10000
BEGIN
SET @id = @id + 1;
insert into eidmadm.PerfData1 (id, c1) values (@id, concat( 'item ', @id) );
if @id % 2 = 0
begin
insert into eidmadm.PerfData2 (fkId, c1) values (@id, concat( 'SubItem ', @id, '-', 1) );
insert into eidmadm.PerfData2 (fkId, c1) values (@id, concat( 'SubItem ', @id, '-', 2) );
insert into eidmadm.PerfData2 (fkId, c1) values (@id, concat( 'SubItem ', @id, '-', 3) );
end;
END;
end;
go
Here is my query
SELECT
Union_Tbl_Alias.*,
ROW_NUMBER() OVER(PARTITION BY id ORDER BY id) toprow,
--RANK() OVER (PARTITION BY id ORDER BY id, subitem desc) AS Rank
DENSE_RANK() OVER (ORDER BY id) AS Rank
FROM
(
SELECT
eidmadm.PerfData1.id,
eidmadm.PerfData1.c1 item,
eidmadm.PerfData2.c1 subitem--,
FROM
eidmadm.PerfData1 inner join
eidmadm.PerfData2 on eidmadm.PerfData1.id = eidmadm.PerfData2.fkId
WHERE (1 = 1)
UNION
SELECT
eidmadm.PerfData1.id,
eidmadm.PerfData1.c1 item,
eidmadm.PerfData2.c1 subitem--,
FROM
eidmadm.PerfData1 left join
eidmadm.PerfData2 on eidmadm.PerfData1.id = eidmadm.PerfData2.fkId
WHERE (1 = 1) and eidmadm.PerfData2.fkId is NULL
) Union_Tbl_Alias
ORDER BY
id, subitem desc
OFFSET 0 ROWS
FETCH NEXT 5000 ROWS ONLY
The Resultset is looking good
id | item | subitem | toprow | Rank |
---|---|---|---|---|
1 | item 1 | NULL | 1 | 1 |
2 | item 2 | SubItem 2-3 | 1 | 2 |
2 | item 2 | SubItem 2-2 | 2 | 2 |
2 | item 2 | SubItem 2-1 | 3 | 2 |
3 | item 3 | NULL | 1 | 3 |
4 | item 4 | SubItem 4-3 | 1 | 4 |
4 | item 4 | SubItem 4-2 | 2 | 4 |
4 | item 4 | SubItem 4-1 | 3 | 4 |
5 | item 5 | NULL | 1 | 5 |
6 | item 6 | SubItem 6-3 | 1 | 6 |
Is it possible to find what is the lowest rank without doing GROUP BY
? I am OK if this query becomes inline view in the wrapping query.