【问题标题】:Insert into a table using multiple tables [duplicate]使用多个表插入一个表[重复]
【发布时间】:2018-12-10 16:18:44
【问题描述】:

我是使用 SQL Server 的新手。我有一个作业,但讲师没有向我们展示如何使用他希望完成作业的工具。

我正在尝试提出一个查询,它将 3 维表的主键插入到另一个表中,并尝试将源数据中的数据插入另一个表中。

源数据是 Google Play 商店中 10000 多个应用的​​数据集。

请看下面我的桌子和我需要的东西

DimContentRating - 有 6 个内容分级

ContentRatingID(PK)   Content Rating
---------------       --------------
1                     Everyone
2                     Teen

DimCategory - 有 34 个类别

CategoryID(PK)   Category
----------       --------
1                Education
2                Finance

DimInstalls - 有很多安装范围

InstallID(PK)  Installs
----------     --------
1              10000+
2              100000+

googleplaystore - 包含 10000+ 条记录和原始数据的表

App       Category  Rating  Reviews  Installs  Price  Content_Rating  
---       --------  ------  ------   --------  -----  --------------
GMAT 
Question  Education  4.2     240      10000+    Free    Everyone
Bank

Ace Elite Finance    4.1     2898     100000+   Free    Everyone

我需要它的外观

AppFact - 需要从上面的表中分解并使用外键链接插入的表

AppFactID    Category  Rating  Reviews  Installs  Price  Content_Rating  
---------    --------  ------  ------   --------  -----  --------------
1              1        4.2     240       1        Free       1
2              2        4.1     2898       2       Free       1

我很抱歉没有尝试编写查询以使其正常工作,但我没有得到太多关于 SQL Server 的信息,因此我所知道的最好的是一般查询。我所知道的是我需要使用以下以及可能的内部连接?

INSERT INTO AppFact(...) 
    SELECT ... 
    FROM ... 

我走对了吗?

【问题讨论】:

标签: sql sql-server ssms sql-server-2017


【解决方案1】:

假设您已经使用 PK AppFactID 创建了表 AppFact,那么您要查找的查询是:

INSERT INTO AppFact (Category, Rating, Reviews, Installs, Price, Content_Rating)
SELECT c.CategoryID, a.Rating, a.Reviews, i.Installs, a.Price, r.ContentRatingID
FROM googleplaystore a
    INNER JOIN DimContentRating r ON a.Content_Rating = r.Content_Rating
    INNER JOIN DimCategory c ON a.Category = c.Category
    INNER JOIN DimInstalls i ON a.Installs = i.Installs

你应该看看JOINs in SQL Server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多