Replace row value with empty string if duplicate

北战南征 提交于 2019-12-17 20:31:01

问题


is it possible to replace row value with empty string if duplicate value found?

For example

SELECT ProductCode, Color FROM Product

--------------------
ProductCode | Color
--------------------
   00A0B    |  Red
   00A0B    |  Blue
   00A0C    |  Red
   00A0C    |  Black
   00A0C    |  White
--------------------

to

--------------------
ProductCode | Color
--------------------
   00A0B    |  Red
            |  Blue
   00A0C    |  Red
            |  Black
            |  White
--------------------

I'm using SQL Server 2012.


回答1:


Often, this type of transformation is better done at the application layer, because the result-set is not "SQL-ish". That is, the ordering is important for understanding the rows.

But, you can do this as:

select (case when row_number() over (partition by ProductCode order by (select NULL)) = 1
             then ProductCode
        end) as ProductCode
       Color
from Product
order by ProductCode;



回答2:


Use ROW_NUMBER and CASE:

WITH Cte AS(
    SELECT *,
        Rn = ROW_NUMBER() OVER(PARTITION BY ProductCode ORDER BY (SELECT NULL))
    FROM Product
)
SELECT
    ProductCode = CASE WHEN Rn = 1 THEN c.ProductCode ELSE '' END,
    Color 
FROM Cte c
ORDER BY c.ProductCode



回答3:


ROW_NUMBER() helps to find duplicate record : 

 SELECT Productcode=( CASE
                           WHEN rn > 1 THEN ''
                           ELSE Productcode
                         END ),
           color
    FROM   (SELECT Row_number()
                     OVER (
                       partition BY productcode
                       ORDER BY productcode) AS rn,
                   *
            FROM   table)a 


来源:https://stackoverflow.com/questions/33138663/replace-row-value-with-empty-string-if-duplicate

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