如何在基于另一个表列数据插入新表时跳过重复数据

时间:2018-06-11 03:23:26

标签: sql sql-server sql-server-2008 sql-server-2012 temp-tables

下面是我的查询,它从组织表中获取记录并根据生产者代码插入到userdetails表中,但是一些生产者代码具有重复值,而Userlogin将不允许重复,因此我使用GROUP BY生成器代码。

但是当我尝试运行以下查询时,我收到以下错误:

  

列' organisation.OrganisationID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

查询:

IF OBJECT_ID('_temp_new_user_details') IS NOT NULL
     DROP TABLE _temp_new_user_details;

SELECT TOP 0 UserID
INTO _temp_new_user_details
FROM UserProductMapping 

INSERT INTO UserDetails (userlogin, Organisationid, emailaddress, username, userpassword, LastModifiedDate, SavedBy, ReceiveEmail, [Disabled])
OUTPUT inserted.UserID INTO _temp_new_user_details --all USerIDs will be saved into _temp_new_user_details
    SELECT 
        '1Qchubb'+ producercode, organisationid, 'demo@chubb.com',
        producercode + N'ii', '123', @CurrentDate, 1, 0, 0
    FROM 
        organisation 
    WHERE 
        producercode != N'00000' 
        AND producercode != '' 
        AND Active = 1 
    GROUP BY 
        producercode

1 个答案:

答案 0 :(得分:1)

假设1个生产者代码只有1个组织ID

SELECT 
    '1Qchubb'+ producercode, organisationid, 'demo@chubb.com',
    producercode + N'ii', '123', @CurrentDate, 1, 0, 0
    ROW_NUMBER() OVER(PARTITION BY PRODUCERCODE ORDER BY PRODUCERCODE, ORGANIZATIONID) AS RNK
INTO #TEMP
FROM 
    organisation 
WHERE 
    producercode != N'00000' 
    AND producercode != '' 
    AND Active = 1 
GROUP BY 
    producercode

INSERT INTO UserDetails (userlogin, Organisationid, emailaddress, username, userpassword, LastModifiedDate, SavedBy, ReceiveEmail, [Disabled])
OUTPUT inserted.UserID INTO _temp_new_user_details
SELECT * FROM #TEMP WHERE RNK = 1

假设1个生产者代码具有多个组织ID,该组织ID基于唯一的producercode和organizationid

SELECT 
    '1Qchubb'+ producercode, organisationid, 'demo@chubb.com',
    producercode + N'ii', '123', @CurrentDate, 1, 0, 0
    ROW_NUMBER() OVER(PARTITION BY PRODUCERCODE, ORGANIZATIONID ORDER BY PRODUCERCODE, ORGANIZATIONID) AS RNK
INTO #TEMP
FROM 
    organisation 
WHERE 
    producercode != N'00000' 
    AND producercode != '' 
    AND Active = 1 
GROUP BY 
    producercode

INSERT INTO UserDetails (userlogin, Organisationid, emailaddress, username, userpassword, LastModifiedDate, SavedBy, ReceiveEmail, [Disabled])
OUTPUT inserted.UserID INTO _temp_new_user_details
SELECT * FROM #TEMP WHERE RNK = 1