我們正在設計一個解決方案,該解決方案將詢問事務資料,以便根據回傳結果的第一組規則回傳匹配,其中每個選擇都比前一個更寬。目標是獲得回傳結果的最窄搜索。
這是一個插圖。考慮具有車輛資料的場景,其中我們獲得了以下三個值:
- 車輛的VIN
- 車輛登記號
- 車輛所在城市
然后,我們想要查詢交易資料以回傳與該值匹配的內容。一個重要的區別是它可以是一對多的匹配,因為交易資料具有額外的關系,這意味著重復的車輛可能駐留在交易資料中。在一對多匹配中,我們需要匹配程序中的所有匹配 ID
我們要查詢資料的順序如下(作為說明):
從交易資料來看:
- 歸還所有具有匹配 VIN 和城市的車輛
如果不存在:
- 退回所有具有匹配 VIN 的車輛
如果不存在:
- 歸還所有具有匹配 Rego 和 City 的車輛
這個例子只有三個加寬條件,然而,在我們的應用程式中它實際上是 8 左右。
這可以按順序進行,如下圖所示,但是感覺不正確,可能有更好的基于集合的操作來做到這一點,但我不知道如何創建它。
以下是可以按順序完成的方式:
-- assume these values are passed in
declare @vin varchar(50) = 'abcdefg'
declare @rego varchar(50) = '123456'
declare @city = 'Sydney'
-- create a table to hold the results
declare @ids table(id int)
-- try the narrowest search: matching VIN and City
insert into @ids(id)
select id from TransactionalData where Vin = @vin and City = @city
if ((select count(*) from @ids ) = 0)
begin
-- try the next narrowest search: matching VIN
insert into @ids(id)
select id from TransactionalData where Vin = @vin
if ((select count(*) from @ids ) = 0)
begin
-- try the next narrowest search: matching Rego and City
insert into @ids(id)
select id from trasnactionaldata where Rego = @rego and City = @city
end
end
-- at this point, @ids will contain the ids from the narrowest search
它會起作用,但它似乎不是正確的方法。誰能建議如何在基于單一集合的操作中做到這一點?
非常感謝
uj5u.com熱心網友回復:
如果我理解正確,我們可以使用列來表示優先級,這意味著您希望按CASE WHEN運算式插入順序
;WITH CTE AS (
SELECT id, CASE WHEN Vin = @vin and City = @city THEN 3
WHEN Vin = @vin THEN 2
WHEN Rego = @rego and City = @cit THEN 1
END priority
FROM TransactionalData where (Vin = @vin and City = @city) OR (Vin = @vin) OR (Rego = @rego and City = @city)
)
INSERT INTO @ids(id)
SELECT id
FROM CTE c
WHERE priority = (SELECT MAX(priority) FROM CTE)
uj5u.com熱心網友回復:
也許是這樣的。您在子句中指定所需的條件,WHERE然后對結果進行匹配計數并對其進行排名
select *,
match_cnt = case when td.vin = @vin then 1 else 0 end
case when td.rego = @rego then 1 else 0 end
case when td.city = @city then 1 else 0 end
from TransactionalData td
where td.vin = @vin
or td.rego = @rego
or td.city = @city
order by match_cnt desc
uj5u.com熱心網友回復:
一種方法是使用EXISTS而不是COUNT
你也可以使用CASE
WITH CTE AS (
SELECT
id,
CASE
WHEN Vin = @vin and City = @city then 1
WHEN Vin = @vin then 2
WHEN Rego = @rego and City = @city then 3
END as lvl
FROM TransactionalData
)
INSERT into @ids(id)
SELECT
id
FROM
CTE
WHERE
lvl = (SELECT MIN(lvl) FROM CTE)
但是你的方法是正確的
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466145.html
上一篇:如何在SSIS中將平面檔案名配置為filename_*.txt
下一篇:比較規范化資料的多條記錄
