选择记录的场景

时间:2017-11-15 23:32:32

标签: sql sql-server etl

我有一个方案可以从数据库中的多个记录中获取少量记录。 以下来源记录属于一个帐户持有人。

PrimaryOrSecondary  Duplicate_Account_ID    Account_ID  START_DATE  END_DATE
------------------  --------------------  ------------  ----------  --------
Primary     1000    1000    26/05/2017    NULL

Primary     1000    1000    10/03/2014    25/05/2017

Secondary   2000    1000    26/05/2017    NULL

Secondary   3000    1000    10/03/2014    25/05/2017

在这4条记录中,我必须在规则下方应用以获得一条目标记录。

  1. 如果Duplicate_Account_ID = Account_ID(那么它是PRIMARY记录),如果其END_DATE为NULL,则在目标中填充该记录,不再查看。

  2. 如果在步骤1中END_DATE为空,则转到辅助记录,其中Duplicate_Account_ID<> Account_ID,并查看是否有任何记录为END_DATE。如果找到,则在目标中填充该记录。

  3. 如果在步骤2中找不到记录,则返回主记录并获取具有最大START_DATE的记录并在目标中填充该记录。

  4. 最终,我需要来自源中这4条记录的目标表中的一条记录。

    任何帮助。

1 个答案:

答案 0 :(得分:1)

您尚未标记DBMS,但这是SQL Server解决方案

INSERT  INTO yourothertable
SELECT  TOP 1
        PrimaryOrSecondary,
        Duplicate_Account_ID,
        Account_ID,
        START_DATE,
        END_DATE
FROM    (
            SELECT  *,
                    MAX(START_DATE) OVER (PARTITION BY PrimaryOrSecondary) AS MaxDate
            FROM    yourtable
        ) a
WHERE   (Duplicate_Account_ID = Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL) OR
        (PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE)
ORDER BY
        CASE
            WHEN Duplicate_Account_ID = Account_ID AND END_DATE IS NULL
            THEN 1
            WHEN PrimaryOrSecondary = 'Secondary' AND Duplicate_Account_ID<>Account_ID AND END_DATE IS NULL
            THEN 2
            WHEN PrimaryOrSecondary = 'Primary' AND MaxDate = START_DATE
            THEN 3
        END