2015-10-15 21 views
0

如果找到重复值,是否可以用空字符串替换行值?如果重复,则用空字符串替换行值

例如

SELECT ProductCode, Color FROM Product 

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

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

我使用SQL Server 2012的

回答

1

通常情况下,这种类型的转换是在应用层做得更好,因为结果-set不是“SQL-ish”。也就是说,排序对理解行很重要。

但是,你能够做到这一点是:

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; 
1

使用ROW_NUMBERCASE

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 
0
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