SQL Server Count values that matches values with other columns

5q4ezhmt  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(139)

SQL - Count number of columns that are having matching values then add count to the additional column.

Assuming I have a temp table with this value
| id | prod_name | attr1 | attr2 | attr3 | attr4 |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | test name | brand | bottle | size | 12x |

then I will need to compare it to product table having values of column by column:

idprod_nameattr1attr2attr3attr4
3test namebrandbottlesize12x
4some namebrandsatchetsize1x
5samplebrandbottlesize23x

expected result should be:

idprod_nameattr1attr2attr3attr4CNT_Match_cols
3test namebrandbottlesize12x4
4some namebrandsatchetsize1x2
5samplebrandbottlesize23x3

*CNT_Match_cols column is get of how many attr(X) columns that are having same values.

holgip5t

holgip5t1#

You can cross join your tables and then count the attribute matches:

select prod.id, prod.prod_name, prod.attr1, prod.attr2, prod.attr3, prod.attr4
,   case when temp.attr1 = prod.attr1 then 1 else 0 end
    + case when temp.attr2 = prod.attr2 then 1 else 0 end
    + case when temp.attr3 = prod.attr3 then 1 else 0 end
    + case when temp.attr4 = prod.attr4 then 1 else 0 end as matched
from (
    VALUES  (1, N'test name', N'brand', N'bottle', N'size', N'12x')
) temp (id,prod_name,attr1,attr2,attr3,attr4)
cross join (
    VALUES  (3, N'test name', N'brand', N'bottle', N'size', N'12x')
    ,   (4, N'some name', N'brand', N'satchet', N'size', N'1x')
    ,   (5, N'sample', N'brand', N'bottle', N'size', N'23x')
) prod (id,prod_name,attr1,attr2,attr3,attr4)

相关问题