取得与MS SQL中的联接的最佳匹配

时间:2018-10-05 07:49:27

标签: sql-server database

我想从Ms SQL查询中获取结果,并按最佳匹配排序。这意味着我有两个这样的表

CREATE TABLE #Leads(
    Id          INT IDENTITY(1,1),
    LeadId      INT,
    PlanId      INT,
    RegionCode  VARCHAR(20),
    FuelType    VARCHAR(20)
)

CREATE TABLE #Discounts(
    Id              INT IDENTITY(1,1),
    PlanId          INT,
    RegionCode      VARCHAR(20),
    FuelType        VARCHAR(20),
    DiscountPercent DECIMAL(6,3)
)

这些表具有以下类似的值

INSERT INTO #Leads([LeadId], [PlanId], [RegionCode], [FuelType])
    VALUES (1,1,'HR26', 'Petrol'),  
           (2,2,'HR30', 'Diesel')

INSERT INTO #Discounts ([PlanId], [RegionCode], [FuelType], [DiscountPercent])
                VALUES (1, null, null, 20),
                       (2, null, null, 10),
                       (2, 'HR30', null, 15),
                       (2, null, 'Diesel', 20),
                       (2, 'HR30', 'Diesel', 25)

因此,如果我们通过#leads#discounts表与PlanId表联接,则-

对于Plan 1,我们没有多个折扣条目,因此我们将选择第一个为20%

但是对于计划2,我们获得的数据为:-

案例1:现在,对于计划2,我们有多个折扣条目,在当前情况下,应该选择25%的折扣,因为RegionCodeFuelType都与潜在客户匹配。

情况2:如果我更新了Plan 2销售线索并更改了RegionCode to NULL(或折扣表中与Plan 2不匹配的任何值),应该选择20%.

案例3:如果我更新了Plan 2线索并更改了FuelType to NULL(或Plan 2折扣表中不匹配的任何值)和RegionCode回到HR30,然后选择15%

情况4::如果我将两者都更改为NULL(或折扣表中与Plan 2不匹配的任何值),则应选择{{ 1}}

我想要最合适的10%.

我不知道该如何写查询,请帮忙-谢谢。

3 个答案:

答案 0 :(得分:0)

假设我理解这个问题,这是解决问题的一种方法:

;WITH CTE AS
(
SELECT  LeadID, 
        (
        CASE WHEN l.RegionCode = d.RegionCode THEN 1 ELSE 0 END
        + CASE WHEN l.FuelType = d.FuelType THEN 1 ELSE 0 END
        -- + more of the same here
        ) As Match,    
        d.DiscountPercent
FROM #Leads As l
JOIN #Discounts As d
    ON l.PlanId = d.PlanId
)

SELECT TOP 1 WITH TIES LeadID, DiscountPercent
FROM CTE
ORDER BY ROW_NUMBER() OVER(PARTITION BY LeadID ORDER BY Match DESC)

答案 1 :(得分:0)

也许我可以从我的经验中获得帮助。但是我只能根据情况查询。

案例1:

SELECT * FROM #Leads l INNER JOIN #Discounts d ON l.PlanId = d.PlanId AND l.RegionCode = d.RegionCode and l.FueLType = d.FuelType

案例2:

SELECT * FROM #Leads l INNER JOIN #Discounts d ON l.PlanId = d.PlanId AND l.FuelType = d.FuelType

情况3:

SELECT * FROM #Leads l INNER JOIN #Discounts d ON l.PlanId = d.PlanId AND l.RegionCode= d.RegionCode

情况4:

SELECT * FROM #Leads l INNER JOIN #Discounts d ON l.PlanId = d.PlanId

这就是我所能帮助的。也许它可以给您一些想法或某些东西。也许更有经验的人可以提供帮助。祝你好运!

答案 2 :(得分:0)

尝试一下:

select * from #Leads l  
join #Discounts d  
   on d.PlanId=l.PlanId  
   and d.[DiscountPercent]=(select max([DiscountPercent]) from #Discounts 
                          where PlanId=l.PlanId 
                          and ((FuelType=l.FuelType and RegionCode=l.RegionCode)
                            or (FuelType=l.FuelType and RegionCode is null)
                            or (FuelType is null and RegionCode=l.RegionCode)
                            or (FuelType is null and RegionCode is null)))