0

how could we remove or not displaying duplicate row with some conditional clause in sqlserver query, the case look like this one,

code    decs
-------------------------
G-006   New
G-006   Re-Registration

how can we display just G-006 with Re-Registration Desc, i have tried with this query but no luck either

with x as (
            select  new_registration_no,category,rn = row_number()
      over(PARTITION BY new_registration_no order by new_registration_no)
      from  equipment_registrations 
)
select * from x

1 Answer 1

1

By using the same field in the PARTITION BY and ORDER BY clause, the rn field will always equal 1.

Assuming that new_registration_no = code and category = decs, you could change the ORDER BY field to be ORDER BY category DESC to get that result. However, that's a pretty arbitrary ORDER BY - you're just basing it on a random text value. I'm also not 100% sure how well the ROW_NUMBER() function works in a CTE.

A better solution might be something like:

SELECT *
FROM 
  (
    SELECT 
        New_Registration_No, 
        Category, 
        ROW_NUMBER() OVER 
          (
            PARTITION BY New_Registration_No 
            ORDER BY 
                CASE 
                    WHEN Category = 'Re-Registration' THEN 1
                    WHEN Category = 'New' THEN 2
                    ELSE 3
                END ASC ) rn
    FROM Equipment_Registrations
  ) s
WHERE rn = 1

You can set the order in the CASE statement to be whatever you want - I'm afraid that without more information, that's the best solution I can offer you. If you have a known list of values that might appear in that field, it should be easy; if not, it will be a little harder to configure, but that will be based on business rules that you did not include in your original post.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.