public SqlQuery QueryVersions(DatasetInfo baseTable, DatasetInfo versionedTable, Expression expression) { var sql = new SqlBuilder(adapter); var v = new SchemaObject(versionedTable.Name, "v"); var a = new SchemaObject(baseTable.Name, "a"); sql.Append("SELECT "); sql.WriteColumns(versionedTable.Members, prefix: "v"); // mutable values, primary keys, ... sql.Append(", "); sql.WriteColumns(baseTable.Members.Where(m => !m.IsVersion && !m.IsKey && !m.IsMutable), prefix: "a"); // immutable values from base table sql.From(v); // SELECT from v var keyName = baseTable.PrimaryKey[0].Name; // join the base (immutable) values with the versioned values sql.InnerJoin( baseTable : v, // versioned values joinedTable : a, // base values baseColumn : keyName, joinedColumn : keyName ); sql.Where(Expand(expression, baseTable)); return new SqlQuery(sql.ToString(), sql.Parameters); }