SQL基于多个规则合并记录

时间:2017-12-14 16:28:31

标签: sql merge rules

以下是表格数据

var stat = missing_stat();
function missing_stat(){
    template ="noun verb apples .that is why he is so adj .  also noun verb apples but he is so adj . noun verb oranges ";
    var fields =template.split(' ');
    for (i=0;i<fields.length;i++)
    {
        if(fields[i]=='noun'){
            fields[i]= noun_change();


        }
        var add = function () {
                var counter = 0;
                return counter += 1;
        };

        function count_change(){
            var count_noun= add();

        }
    }
}

规则是:

  1. 对于帐户,合并具有相同到期日期的政策
  2. 对于帐户,合并具有相同状态的策略
  3. 选择合并每个帐户的最新政策
  4. 合并政策,车辆类型如下 一个。 MC&amp; TR(如果一个策略有MC,其他有TR,则合并) 湾PP(PP不能与任何其他类型合并) C。 SO(SO不能与任何其他类型合并)
  5. 输出应为

    AccountID PolicyNumber State Policy_Expiration_Dt VehicleTypeCode
    -----------------------------------------------------------------------------------------------
    80102 100 CA 21-12-2017 MC
    80102 101 CA 21-12-2017 TR
    80102   102 CA 21-12-2017 PP
    80103 104 IL 14-12-2017 SO
    80103 105 IL 14-12-2017 PP
    

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

--------- CREATING EXAMPLE
CREATE TABLE #Something (
    AccountID INT
    ,PolicyNumber INT
    ,[State] CHAR(2)
    ,Policy_Expiration_Dt DATE
    ,VehicleTypeCode CHAR(2)
    )

INSERT INTO #Something
SELECT 80102,100,'CA','12-21-2017','MC'
UNION ALL SELECT 80102,101,'CA','12-21-2017','TR'
UNION ALL SELECT 80102,102,'CA','12-21-2017','PP'
UNION ALL SELECT 80103,104,'IL','12-14-2017','SO'
UNION ALL SELECT 80103,105,'IL','12-14-2017','PP'
---------END

SELECT a.AccountID
    ,a.Policy_Expiration_Dt
    ,a.[state]
    ,a.VehicleTypeCode
FROM (
    SELECT AccountID
        ,Policy_Expiration_Dt
        ,[state]
        ,CASE 
            WHEN VehicleTypeCode = 'TR'
                THEN 'MC'
            ELSE VehicleTypeCode
            END AS 'VehicleTypeCode'
    FROM #Something
    ) a
GROUP BY a.AccountID
    ,a.Policy_Expiration_Dt
    ,a.[state]
    ,a.VehicleTypeCode