如何使重复值唯一?

时间:2014-02-27 08:48:01

标签: sql sql-server-2012 ssms

我在列中有重复值的记录。

例如:

INVOICENUM  PRODUCT
-------------------
  789789    ABROPT
  789789    ABROPT
  719648    AZGTEL
  754114    GRTYPT

我有2条重复发票编号的记录,第一个数字我要为第二个添加'a'我要添加'b'等等。

INVOICENUM  PRODUCT
-------------------
 789789a    ABROPT
 789789b    ABROPT
 719648     AZGTEL
 754114     GRTYPT

如何使用SQL解决此问题 - 我使用的是SQL Server 2012和Microsoft SQL Server Management Studio 11.0.3000.0?

2 个答案:

答案 0 :(得分:2)

这些问题通常是通过分析函数来解决的。

select case
         when (count(1) over(partition by InvoiceNum) > 1) then
           InvoiceNum + Char(row_Number() over(partition by InvoiceNum order by InvoiceNum) + 96)
         else
           InvoiceNum
       end as InvoiceNum,
       Product    
  from MyTable

分析函数的主要优势性能

答案 1 :(得分:1)

好吧假设SQL Server(具有rownumber功能),那么这似乎可行

select
    INVOICENUM = case 
        when INVOICENUM in (select INVOICENUM from YourTable group by INVOICENUM having COUNT(*) > 1)
        then INVOICENUM + char(96+row_number() over (partition by INVOICENUM order by INVOICENUM))
        else INVOICENUM 
    end,
    PRODUCT,
    OtherColumn,
    AnotherColumn
from 
    YourTable

虽然不是特别优雅......

这里的想法是获取一个行号来为int-to-character函数CHAR(...)设定种子。其中96是 a 之前的字符的ASCII码 - 所以rownumber为1给出 a (即Ascii代码为97),行号为2给出 b < / strong>(即Ascii代码为98)等等...... 我在那里抛出case语句以排除没有重复的情况,所以它只是在没有添加字母的情况下返回InvoiceNum ...

继承我的测试示例......

declare @data table (INVOICENUM nvarchar(100), PRODUCT nvarchar(100))

insert into @data
values ('789789', 'ABROPT')
,('789789', 'ABROPT')
,('719648', 'AZGTEL')
,('754114', 'GRTYPT')

select
    INVOICENUM = case 
        when INVOICENUM in (select INVOICENUM from @data group by INVOICENUM having COUNT(*) > 1)
        then INVOICENUM + char(96+row_number() over (partition by INVOICENUM order by INVOICENUM))
        else INVOICENUM 
    end,
    PRODUCT
from 
    @data