The number of differences in a column

后端 未结 5 1131
情深已故
情深已故 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 07:39

    You read a next record with LEAD. Then compare the strings with LIKE or other string functions:

    select
      id, value, category,
      case when value like next_value + '%' or next_value like value + '%' 
           then len(next_value) - len(value)
      end as differences
    from
    (
      select id, value, category, lead(value) over (order by id) as next_value 
      from mytable
    ) this_and_next;
    

    If you only want to compare values within the same category use a partition clause:

    lead(value) over (partition by category order by id)
    

    UPDATE: Please see DhruvJoshi's answer on SQL Server's LEN. This function doesn't count trailing blanks, as I assumed, so you need his trick in case you want to have them counted. Here is the doc on LEN confirming this behaviour: https://technet.microsoft.com/en-us/library/ms190329(v=sql.105).aspx

提交回复
热议问题