[英]How to get the best matching result from the below table?
ID | Company | Type --- | -------- | ---- 1 | * | * 2 | CMP1 | * 3 | CMP1 | TYP1 4 | * | TYP1 5 | * | TYP2 6 | CMP1 | TYP2
(Here Company and Type together makes the Primary Key.) (这里公司和类型一起制作主键。)
I have to get the exact match from this table. 我必须从这张表中得到完全匹配。 My different inputs are
我的不同投入是
Company | Type | OutPut ----- | ----- | ------- CMP1 | TYP1 | 3 CMP2 | TYP2 | 5 CMP5 | TYP5 | 1If the company is matching with any record get that one otherwise look for the * value.
(Currently I did looping each fields and assign a score by best matches, and after that I am getting the top 1 by score value.) Is there any simple way ? (目前我确实循环每个字段并通过最佳匹配分配得分,之后我按得分值获得前1名。)有没有简单的方法?
You can do this using outer apply
: 您可以使用
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;
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
You could try bellow solution: 您可以尝试以下解决方案:
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
Results: 结果:
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
Notes: 笔记:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.