插入SQL表

时间:2014-10-21 20:01:24

标签: sql sql-server sql-server-2008

我试图将发票编号从一个数据库插入另一个数据库。新数据库invoiceNo是主键。原始数据库中有重复的发票号。我使用

找到了重复项
SELECT  SERIAL_NO,
COUNT(*) as cnt    
FROM HISTORY_INCIDENTS
group by SERIAL_NO having COUNT(*) > 1
order by COUNT(*) desc

我想在第二张发票的末尾放置一个-1,这样它们就是唯一的。不确定如何做到这一点是SQL

2 个答案:

答案 0 :(得分:2)

您可以使用这样的CTE ......

;
WITH    cteDups
          AS ( SELECT   SERIAL_NO ,
                        RN = ROW_NUMBER() OVER 
              ( PARTITION BY SERIAL_NO ORDER BY SERIAL_NO )
               FROM     HISTORY_INCIDENTS
             )
    SELECT  CASE RN
              WHEN 2 THEN SERIAL_NO + '-1'
              ELSE SERIAL_NO
            END AS SERIAL_NO
    FROM    cteDups

请参阅fiddle。如果有重复的话,这会创建 2 的行号,然后您可以使用CASE检查任何 2 ' s ,并将 -1 分配给该记录。

编辑:根据评论

DECLARE @HISTORY_INCIDENTS TABLE ( SERIAL_NO INT );
DECLARE @NewHISTORY_INCIDENTS TABLE ( SERIAL_NO VARCHAR(10) );

INSERT  INTO @HISTORY_INCIDENTS
        ( SERIAL_NO )
VALUES  ( 1 );
INSERT  INTO @HISTORY_INCIDENTS
        ( SERIAL_NO )
VALUES  ( 2 );
INSERT  INTO @HISTORY_INCIDENTS
        ( SERIAL_NO )
VALUES  ( 2 );
INSERT  INTO @HISTORY_INCIDENTS
        ( SERIAL_NO )
VALUES  ( 2 );

;
WITH    cteDups
          AS ( SELECT   SERIAL_NO ,
                        RN = ROW_NUMBER() OVER ( PARTITION BY SERIAL_NO 
                                                           ORDER BY SERIAL_NO )
               FROM     @HISTORY_INCIDENTS
             )
    INSERT  INTO @NewHISTORY_INCIDENTS
            ( SERIAL_NO
            )
            SELECT  CASE RN
                      WHEN 2 THEN CAST(SERIAL_NO AS VARCHAR(10)) + '-1'
                      ELSE CAST(SERIAL_NO AS VARCHAR(10))
                    END AS SERIAL_NO
            FROM    cteDups

SELECT   SERIAL_NO
FROM    @NewHISTORY_INCIDENTS

答案 1 :(得分:0)

我认为这会奏效。

我使用ROW_NUMBER()函数来计算内部派生表中序列号出现的次数。在主查询中,我根据发现的次数决定如何制作新的序列号。

PS:没有SQL编辑器。

SELECT
     SERIAL_NO
    ,SERIAL_NO + CASE WHEN [SERIAL_NO_Occurrence] > 1 THEN '-' + CAST([SERIAL_NO_Occurrence]-1 AS VARCHAR) ELSE '' END AS [SERIAL_NO_New]
FROM (

    -- inner derived table to select number of occurrences of each serial number
    SELECT      SERIAL_NO
                ,ROW_NUMBER() OVER (
                    PARTITION BY SERIAL_NO
                    ORDER BY SERIAL_NO -- you should also have a PK field here to have deterministic results I think
                 ) AS [SERIAL_NO_Occurrence]
    FROM        HISTORY_INCIDENTS
) AS T1;