i want to top 1 data from each distinct RefNId

i want to top 1 data from each distinct RefNId

Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Mar 18, 2023, 12:54 PM
You can also use CTE that can make the query easier to read and understand. Here's an example
Tuhin PaulPosted Jan 7, 2024, 5:38 PM
@Anandu G Nath
The given SQL query is using a Common Table Expression (CTE) to assign a row number to each row based on the RefNId partition and ordering by Id. The final result selects only the rows where RowNum is equal to 1. This is a common pattern used to retrieve the first row for each group within a partition.
Verify that the indexes are being used appropriately by examining the execution plan. You may need to adjust or add indexes based on the characteristics of your data and query patterns.
something similar to the image shared.
Anandu G NathPosted Jan 6, 2024, 10:43 AM
WITH CTE AS (
SELECT Id, RefNId, NType, RoleId, DeptID,
ROW_NUMBER() OVER (PARTITION BY RefNId ORDER BY Id) AS RowNum
FROM YourTableName
)
SELECT Id, RefNId, NType, RoleId, DeptID, RowNum
FROM CTE
WHERE RowNum = 1;
Tuhin PaulPosted Mar 18, 2023, 12:53 PM
Thanks Naimish for posting,but there are a few ways that this query could be improved:
1. Instead of using ROW_NUMBER() to select the first occurrence of each group, you could use TOP 1 to select only the top row for each RefNId group. This can simplify the query and potentially improve performance.
2. If the table has a large number of rows and the RefNId column is not indexed, adding an index on this column can significantly improve query performance.
3. The data types used for the Id, RefNId, NType, RoleId, and DeptID columns are appropriate for the data being stored. Using smaller data types where possible can also improve query performance.
Naimish MakwanaPosted Mar 18, 2023, 11:20 AM
Hello Sandeep,
Use below query,
Thanks
Naimish Makwana