通过比较2个相同的表来选择最新记录

时间:2016-03-01 04:55:22

标签: sql

我有2个相同的源表,列相同,但只有不同的值。两个表都没有任何主键。

我希望根据这些条件从这两张表中获取最新记录:

  1. 应该比较Test1和Test2,并根据最新的扫描日期和BiosID,它应该返回值。
  2. 如果BiosID为null,则应检查最新扫描日期和SerialNumber。
  3. 如果BiosID和SerialNumber都为空,则应检查主机名。
  4. TEST1:

    MachineID | Scandate   | Account | BiosID     | Serial number | Hostname |
    1000      | 10-01-2016 | A       | Abcd1111   | null          |     null |
    1001      | 11-01-2016 | B       | null       | 7890          |      XYZ |
    1002      | 12-02-2016 | C       | null       | null          |      PQR |
    1003      | 13-01-2016 | D       | null       | null          |      DEF |
    

    的Test2:

    MachineID | Scandate   |    Account |   BiosID  |   Serial number | Hostname |
    1000      | 10-02-2016 |          W |   Abcd1111|            1234 |      ABC |
    1001      | 11-02-2016 |          X |   null    |            7890 |     null |
    1002      | 12-01-2016 |          Y |   null    |            null |     null |
    1003      | 13-02-2016 |          Z |   null    |             null|      DEF |
    

    结果表应该是 TEST3:

    结果:

    MachineID | Scandate   |    Account |   BiosID   |  Serial number | Hostname |
    1000      | 10-02-2016 |          W |   Abcd1111 |           1234 |      ABC |
    1001      | 11-02-2016 |          X |   Null     |           7890 |     null |
    1002      | 12-02-2016 |          C |   null     |           null |      PQR |
    1003      | 13-02-2016 |          Z |   null     |           null |      DEF |
    

    以前,我只编写了一个代码来检查最新的扫描和BiosID。

    查询:

    WITH Combined As(
    SELECT MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName
    FROM TEST1
    
    UNION 
    SELECT MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName
    FROM TEST2
    )
    , Ordered AS(
    SELECT MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName,
    ROW_NUMBER() OVER(PARTITION BY BiosID ORDER BY LastHWScan DESC) AS rn
    FROM Combined
    )
    
    INSERT INTO TEST3(MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName)
    SELECT MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName FROM Ordered
    WHERE rn=1
    

    但是如果BiosID为null,我无法获得所需的结果。 那么有人可以帮助我吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试类似

的内容
ROW_NUMBER() OVER(PARTITION BY BiosID ORDER BY LastHWScan DESC) as rn
, ROW_NUMBER() OVER(ORDER BY LastHWScan, SerialNumber DESC) as rn2
, ROW_NUMBER() OVER(ORDER BY Hostname DESC) as rn3

INSERT INTO TEST3(MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName)
    SELECT MachineID,LastHWScan,Account,BiosID,SerialNumber,HostName FROM Ordered
    WHERE (BiosID IS NOT NULL AND rn = 1)
    OR (BiosID IS NULL AND SerialNumber IS NOT NULL AND rn2 = 1)
    OR (BiosID IS NULL AND SerialNumber IS NULL AND rn3 = 1)