🌐 US-Proxy
class="archive tag tag-sql tag-10346 wp-theme-pubmystique customizer-styles-applied content-sidebar jetpack-reblog-enabled has-marketing-bar has-marketing-bar-theme-mystique">

Blog Archives

Hamming distance on database records

Today I needed to quickly compare multiple records in one table with one I already had and find the most similar one, specifically in MSSQL but the query I used can be modified for most other DB systems. I am going to write this up a little formally to make sure that it is clear. Note: that this implementation can be modified to be a dynamically created query or a stored procedure.

Problem

For a given record in sourceTable (id = 12), rank records in table, based on how many values of each record match the corresponding column:value pair.

Solution

Use a modified hamming distance algorithm in the SQL as follows:

SELECT table.id,

CASE WHEN sourceTable.columnName1 = table.columnName1 THEN 0 ELSE 1 END +
CASE WHEN sourceTable.columnName2 = table.columnName2 THEN 0 ELSE 1 END +
...
CASE WHEN sourceTable.columnNameN = table.columnNameN THEN 0 ELSE 1 END AS hammingDistance
FROM table, sourceTable
WHERE sourceTable.id = 12
 ORDER BY hammingDistance ASC

This implementation of the hamming code algorithm ranks all the records in the [table] table based on how many differences there are between the column values with the same column name in each table. So as output from this query we get the id’s of the table ranked with the most similar first (a hamming distance value of 0 being identical) and the least similar last. I am not sure that this is the most efficient way of doing this but at this point in time it works and can be modified for more complicated comparisons.

MSSQL Update Trick

So today I found a neat trick (that was intuitive but not obvious, at least to me and my google search for “SQL update set column = column”) was that you can set one column to be relative to anther column in the same table.
So in this example my table has 2 columns: buy and sell, initially I have set both to the same value but now I want to add 15% margin onto this. The solution is very simple:

UPDATE table SET sell = buy * 1.15

And like magic all the sell values in the table are 15% higher than the buy price.

Design a site like this with WordPress.com
Get started