从当前表内部连接6个表创建新表

时间:2017-02-10 16:14:39

标签: sql create-table

我对SQL很新,所以如果我的查询看起来不完美,我会提前道歉。我正在尝试为此声明创建一个新表。我在主键上加入了6个表。我尝试创建表格(但它不起作用)。如果有人能取悦我,那将非常感激!

IList<QuerySuggest> QuerySuggestions(
    RequestType request, 
    bool filterByUser = false,
    bool excludeUser = false)
{
    IRepository<QuerySuggest> repository = 
        _repositoryManager.GetRepository<QuerySuggest>(_repositoryType);

    var entities = repository
        .Query(c => c.Where(e => 
            e.IdWebsite == request.WebSiteId &&
            e.FulltextFree != null &&
            e.DataOra >= (System.DateTime.Today.AddDays(-60).Date) &&
            (!filterByUser || e.UserId == request.UserId) &&
            (!excludeUser || e.UserId != request.UserId)
        )
        .GroupBy(g => g.FulltextFree)
        .Select(n => new { FulltextFree = n.Key, HowMany = n.Count() })
        .Where(w => w.HowMany >= request.HowMany)
        .OrderBy(o => o.HowMany))
        .ToList();

    return entities;
}

IList<QuerySuggest> QuerySuggestionsByUser(RequestType request)
{
    return QuerySuggestions(request, filterByUser: true);
}

IList<QuerySuggest> QuerySuggestionsAnyUser(RequestType request)
{
    return QuerySuggestions(request);
}

IList<QuerySuggest> QuerySuggestionsOtherUsers(RequestType request)
{
    return QuerySuggestions(request, excludeUser: true);
}

1 个答案:

答案 0 :(得分:0)

所以你想要一个包含每个源表中所有字段的表,是吗?您可以使用SELECT .... INTO:

SELECT [Field List] INTO MyNewConsolidatedTable      
FROM DATABASE.Table1
INNER JOIN DATABASE.Table2
ON DATABASE.Table1.PrimaryKey = DATABASE.Table2.PrimaryKey
INNER JOIN DATABASE.Table3
ON DATABASE.Table1.PrimaryKey = DATABASE.Table3.PrimaryKey
INNER JOIN DATABASE.Table4
ON DATABASE.Table1.PrimaryKey = DATABASE.Table4.PrimaryKey
INNER JOIN DATABASE.Table5
ON DATABASE.Table1.PrimaryKey = DATABASE.Table5.PrimaryKey
INNER JOIN DATABASE.Table6
ON DATABASE.Table1.PrimaryKey = DATABASE.Table6.PrimaryKey
WHERE PrimaryKey = ‘1’

请注意,您需要替换[Field List]并枚举新表中所需的所有字段,否则您将有6个名为PrimaryKey的字段,SQL将不允许这样做。