Union of intervals

Sort them by one of the terms (start, for example), then check for overlaps with its (right-hand) neighbor as you move through the list. class tp: def __repr__(self): return “(%d,%d)” % (self.start, self.end) def __init__(self, start, end): self.start = start self.end = end s = [tp(5, 10), tp(7, 8), tp(0, 5)] s.sort(key=lambda self: self.start) y … Read more

Merge two rows in SQL

Aggregate functions may help you out here. Aggregate functions ignore NULLs (at least that’s true on SQL Server, Oracle, and Jet/Access), so you could use a query like this (tested on SQL Server Express 2008 R2): SELECT FK, MAX(Field1) AS Field1, MAX(Field2) AS Field2 FROM table1 GROUP BY FK; I used MAX, but any aggregate … Read more

Way to try multiple SELECTs till a result is available?

LIKE without wildcard character is equivalent to =. Assuming you actually meant name=”text”. Indexes are the key to performance. Test setup CREATE TABLE image ( image_id serial PRIMARY KEY , group_id int NOT NULL , name text NOT NULL ); Ideally, you create two indexes (in addition to the primary key): CREATE INDEX image_name_grp_idx ON … Read more

Union of multiple ranges

Let’s say, (7, 10) and (11, 13) result into (7, 13): a = [(7, 10), (11, 13), (11, 15), (14, 20), (23, 39)] b = [] for begin,end in sorted(a): if b and b[-1][1] >= begin – 1: b[-1] = (b[-1][0], end) else: b.append((begin, end)) b is now [(7, 20), (23, 39)] EDIT: As @CentAu … Read more

ActiveRecord Query Union

Here’s a quick little module I wrote that allows you to UNION multiple scopes. It also returns the results as an instance of ActiveRecord::Relation. module ActiveRecord::UnionScope def self.included(base) base.send :extend, ClassMethods end module ClassMethods def union_scope(*scopes) id_column = “#{table_name}.id” sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(” UNION “) where “#{id_column} IN (#{sub_query})” end end end … Read more