每行的相似列的总和

时间:2016-07-11 11:15:12

标签: sql postgresql

我有如下表格

doctor_id    forename surname email           ...
 1           jon      doe     jon@doe.com     ...
 2           john     dove    john@dove.com   ...
 3           jane     dane    jane@dane.com   ...
 4           foo      bar     foo@bar.com     ...
 5           bar      foo     bar@foo.com     ...

请考虑我的桌子上还有10多个栏目。

我有一组数据(forename =&#34; jon&#34;,surname =&#34; doe&#34;,email =&#34; foo@bar.com"等)< / p>

我想检查每一行中与数据集中的列具有相同值的列数

doctor_id    forename surname email           ...   similiarities
 1           jon      doe     jon@doe.com     ...   2
 2           john     dove    john@dove.com   ...   0
 3           jane     dane    jane@dane.com   ...   0
 4           foo      bar     foo@bar.com     ...   1
 5           bar      foo     bar@foo.com     ...   0

并仅选择具有大于3的相似数的行。

1 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

select t.*,
       ((case when forename = 'jon' then 1 else 0 end) +
        (case when surname = 'doe' then 1 else 0 end) +
        (case when email = 'foo@bar.com' then 1 else 0 end)
       ) as similarities
from t;