如何在sql中组合两个表?

时间:2018-01-05 13:19:57

标签: sql sql-server

使用Sql server 2008我可以返回两个表结果,如下所示 BOTH TABLE CONTAIN SAME DATA AND SIMILAR DATA AS WELL

我正在尝试将这两个表组合在一起,并通过比较PK [PrimaryKeys]来获取重复数据,以获得如上所述的结果。

但我不知道如何做到这一点,任何人都可以帮助我,在此先感谢。

2 个答案:

答案 0 :(得分:2)

只需使用UNION,将自动删除重复项(对于所有所有列的重复项)

INSERT INTO Table3
(
    PayId,
    PayName,
    PayMail,
    PayPhone
)
SELECT
        PayId,
        PayName,
        PayMail,
        PayPhone
        FROM Table1 

    UNION

    SELECT
        PayId,
        PayName,
        PayMail,
        PayPhone
        FROM Table2

或者,如果您只想基于PayId删除重复项。试试这个

;WITH CTE
AS
(
    SELECT
        PayId,
        PayName,
        PayMail,
        PayPhone
        FROM Table1 

    UNION

    SELECT
        PayId,
        PayName,
        PayMail,
        PayPhone
        FROM Table2
),C2
(
    SELECT
        RN = ROW_NUMBER() OVER(PARTITION BY PayId),
        PayId,
        PayName,
        PayMail,
        PayPhone
        FROM CTE
)
INSERT INTO Table3
(
    PayId,
    PayName,
    PayMail,
    PayPhone
)
SELECT
    PayId,
    PayName,
    PayMail,
    PayPhone
    FROM C2
        WHERE RN = 1

答案 1 :(得分:0)

试试这个

;With Table1(Payid,PayName,Paymail,Payphone)
AS
(
SELECT 'MK1234000','John','j40@YPRO.com',1222121        UNION ALL
SELECT 'MK1234002','Brown','BLACKPAI@AC.com',4444455    UNION ALL
SELECT 'MK1234003','GINGER','GK202@YPRO.com',8938343    UNION ALL
SELECT 'MK1234004','LINDA','LACYGIRL@VV.com',8938349    UNION ALL
SELECT 'MK1234008','ANDAN','ANDAN.HR@KYP.com',8938349
)
,Table2(Payid,PayName,Paymail,Payphone)
AS
(
SELECT 'MK1234000','John','j40@YPRO.com',1222121        UNION ALL
SELECT 'MK1234002','Brown','BLACKPAI@AC.com',4444455    UNION ALL
SELECT 'MK1234003','GINGER','GK202@YPRO.com',8938343    UNION ALL
SELECT 'MK1234004','LINDA','LACYGIRL@VV.com',8938349    UNION ALL
SELECT 'MK1234008','ANDAN','ANDAN.HR@KYP.com',8938349   UNION ALL
SELECT 'MK1234009','SAROK','SSKK@Gmail.com',87436222    UNION ALL
SELECT 'MK1234022','YUTHI','YUTHI@Hg.com',92473433
)

SELECT B.* 
FROM Table2 B LEFT JOIN Table1 A
On A.Payid=B.Payid

预期结果

Payid       PayName  Paymail            Payphone
-------------------------------------------------
MK1234000   John    j40@YPRO.com        1222121
MK1234002   Brown   BLACKPAI@AC.com     4444455
MK1234003   GINGER  GK202@YPRO.com      8938343
MK1234004   LINDA   LACYGIRL@VV.com     8938349
MK1234008   ANDAN   ANDAN.HR@KYP.com    8938349
MK1234009   SAROK   SSKK@Gmail.com      87436222
MK1234022   YUTHI   YUTHI@Hg.com        92473433