remove duplicate rows in SQL Server Query

六眼飞鱼酱① 提交于 2019-12-13 07:34:14

问题


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:


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.



来源:https://stackoverflow.com/questions/24322259/remove-duplicate-rows-in-sql-server-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!