如何从下表中获得最佳匹配结果?

时间:2017-01-15 12:30:55

标签: sql sql-server

ID  | Company  | Type  
--- | -------- | ----  
1   | *        |   *   
2   | CMP1     |   *   
3   | CMP1     |  TYP1
4   | *        |  TYP1
5   | *        |  TYP2
6   | CMP1     |  TYP2 

(此处公司和类型一起制作主键。)

我必须从这张表中得到完全匹配。我的不同投入是

Company  | Type  |  OutPut
-----    | ----- |  -------
CMP1     | TYP1  |   3
CMP2     | TYP2  |   5
CMP5     | TYP5  |   1
如果公司与任何记录匹配,则获取该值,否则查找*值。 你怎么得到这个?

(目前我确实循环每个字段并按最佳匹配分配得分,之后我按得分值获得前1名。)有没有简单的方法?

3 个答案:

答案 0 :(得分:0)

您可以使用outer apply

执行此操作
select i.*, t1.id
from inputs i outer apply
     (select top 1 t1.*
      from t1
      where (t1.Company = '*' or t1.Compay = i.Company) or
            (t1.Type = '*' or t1.Type = i.Type)
      order by ((case when t1.company = '*' then 0 else 1 end) +
                (case when t1.type = '*' then 0 else 1 end)
               ) desc
    ) t1;

答案 1 :(得分:0)

SELECT TOP 1 * 
FROM [test]
ORDER BY
        (CASE WHEN Company = @Company  and Type = @Type  THEN 1000 ELSE 0 END
        + CASE WHEN Company = @Company  and Type ='*' THEN 900 ELSE 1 END
        + CASE WHEN Company = '*' and Type = @Type  THEN 800 ELSE 2 END
        + CASE WHEN Company = '*' and Type = '*' THEN 700 ELSE 3 END
        ) DESC

答案 2 :(得分:0)

您可以试试以下解决方案:

DECLARE @Company2Type TABLE (
    ID      INT NOT NULL 
        UNIQUE NONCLUSTERED,
    Company VARCHAR(50) NOT NULL,
    [Type]  VARCHAR(50) NOT NULL,
        PRIMARY KEY CLUSTERED (Company, [Type])     
)
INSERT  @Company2Type
VALUES  
(1, '*',    '*'),
(2, 'CMP1', '*'),
(3, 'CMP1', 'TYP1'),
(4, '*',    'TYP1'),
(5, '*',    'TYP2'),
(6, 'CMP1', 'TYP2');

DECLARE @TestData TABLE (
    Company VARCHAR(50) NOT NULL,
    [Type]  VARCHAR(50) NOT NULL
)
INSERT  @TestData
VALUES  
('CMP1' , 'TYP1'),
('CMP2' , 'TYP2'),
('CMP5' , 'TYP5');

SELECT  *, COALESCE(rule1.ID, rule2.ID, rule3.ID, rule4.ID) AS [Output]
FROM    @TestData td
OUTER APPLY (
    SELECT  ct.ID
    FROM    @Company2Type ct
    WHERE   ct.Company = td.Company
    AND     ct.[Type] = td.[Type]
) rule1 
OUTER APPLY (
    SELECT  ct.ID
    FROM    @Company2Type ct
    WHERE   rule1.ID IS NULL
    AND     ct.Company = td.Company
    AND     ct.[Type] = '*'
) rule2
OUTER APPLY (
    SELECT  ct.ID
    FROM    @Company2Type ct
    WHERE   rule1.ID IS NULL
    AND     ct.Company = '*'
    AND     ct.[Type] = td.[Type]
) rule3
OUTER APPLY (
    SELECT  ct.ID
    FROM    @Company2Type ct
    WHERE   rule1.ID IS NULL
    AND     ct.Company = '*'
    AND     ct.[Type] = '*'
) rule4

结果:

Company Type ID   ID   ID   ID   Output
------- ---- ---- ---- ---- ---- ------
CMP1    TYP1 3    NULL NULL NULL 3
CMP2    TYP2 NULL NULL 5    1    5
CMP5    TYP5 NULL NULL NULL 1    1

注意:

  • [Rule1]公司和类型都匹配
  • [Rule2]公司匹配并测试类型匹配*
  • [Rule3]测试公司匹配*和类型匹配
  • [Rule4]公司和类型都匹配*