The number of differences in a column

后端 未结 5 1129
情深已故
情深已故 2021-01-29 07:18

I would like to retrieve a column of how many differences in letters in each row. For instance

If you have a a value \"test\" and another row has a value \"testing \", t

5条回答
  •  [愿得一人]
    2021-01-29 08:02

    you can also use self joining query like below:

    --create table tbl (id int,  value nvarchar(100), category int);
    --insert into tbl values
    --(1,N'test',1)
    --,(2,N' testing',1)
    --,(11,N'candy',2)      
    --,(12,N'ca',2);
    select A.*, LEN(B.value)-LEN(A.value) as difference
    from tbl A LEFT JOIN tbl B on A.id +1 =B.id and A.category=B.category
    --drop table tbl
    

    Update: I noticed that you have oddly positioned the space at the end. SQL server most times does not count the trailing spaces when calculating length. So here's the hack on above query

    select A.*, LEN(B.value+'>')-LEN(A.value+'>') as difference
    from tbl A LEFT JOIN tbl B on A.id +1 =B.id and A.category=B.category
    

    As pointed out in comments, that Id's may not be consecutive, in such cases try this :

    create table #temp ( rownum int PRIMARY KEY IDENTITY(1,1), id int, value nvarchar(100), category int)
    insert into #temp (id, value, category)
    select id, value, category from tbl order by id asc
    
    
        select A.id, A.value, A.category, LEN(B.value+'>')-LEN(A.value+'>') as difference
        from #temp A LEFT JOIN #temp B on A.rownum +1 =B.rownum and A.category=B.category
    

提交回复
热议问题