SQL Server Best of X Comparison

I am trying to fulfill a query that can return me results in which most of the 5 conditions are met. But if there is one match 5 out of 5, then this takes precedence.

To illustrate my question, the following SQL code has been prepared.

declare @tmp table (
id int identity
,field1 nvarchar(60)
,field2 nvarchar(60)
,field3 nvarchar(60)
,field4 nvarchar(60)
,field5 nvarchar(60)
)

insert into @tmp values
    ('Bob','Jones','Mr','000001','bob@example.com')
insert into @tmp values
    ('Bill','Jones','','000002','bill@example.com')
insert into @tmp values
    ('Sue','Jones','Mrs','000003','jones@example.com')
insert into @tmp values
    ('Adrian','Jones','','000001','jones@example.com')
insert into @tmp values
    ('Bertha','Jones','Mrs','000001','jones@example.com')

select *
from @tmp

declare @key1 nvarchar(60), @key2 nvarchar(60), @key3 nvarchar(60), @key4 nvarchar(60), @key5 nvarchar(60)

select
    @key1 = 'Bertha'
    ,@key2 = 'Jones'
    ,@key3 = 'Mrs'
    ,@key4 = '000001'
    ,@key5 = 'jones@example.com'

select
    *
    ,case when field1 = @key1 then 1 else 0 end as X1
    ,case when field2 = @key2 then 1 else 0 end as X2
    ,case when field3 = @key3 then 1 else 0 end as X3
    ,case when field4 = @key4 then 1 else 0 end as X4
    ,case when field5 = @key5 then 1 else 0 end as X5
from @tmp

If you look at the results, you will see several lines of 3 and 4 matches in 3 fields, but line 5 corresponds to 5 fields. Therefore, this is an identical coincidence, and the one I want to return.

But if Row 5 was not inserted, then lines 3 and 4 are the best matches, in which case I would like them to come back.

I am trying to think how to do this, I am using SQL Server 2008, if that can make a difference.

In a real scenario, they are not all simple case statements, as in this example, but subsamples to other tables.

, , .

"" , SQL Server?

"", , , . , , SQL, , , .

+3
1

x SUM . CTE (Common Table Expression), .

;with mysum AS (
select    *
    ,case when field1 = @key1 then 1 else 0 end as X1
    ,case when field2 = @key2 then 1 else 0 end as X2
    ,case when field3 = @key3 then 1 else 0 end as X3
    ,case when field4 = @key4 then 1 else 0 end as X4
    ,case when field5 = @key5 then 1 else 0 end as X5
from @tmp)

SELECT id, field1, field2, field3, field4, field5, 
       SUM(x5+x4+x3+x2+x1) AS MatchScore 
FROM MySum
GROUP BY id, field1, field2, field3, field4, field5
ORDER BY MatchScore DESC
+2

All Articles