加入一个 table 与标签的重复条目但不是 ID 列
Join a table with duplicate entries for a label but not for the ID column
我有以下 table Fact_Sales :
ProductSK DateSK SalesAmount SalesNumber
1 2019 300 150
2 2019 500 190
.....
和以下 table DimProduct:
ProductSK CategoryLabel
1 ABC
2 ABC
....
我想按类别标签计算销售额,但是当像下面这样加入时,查询结果生成笛卡尔积:
SELECT CategoryLabel, SUM(SalesAmount)
FROM Fact_Sales, DimProduct
您可以 LEFT 连接到产品的不同值 table :
SELECT DP.CategoryLabel, SUM(FS.SalesAmount)
FROM Fact_Sales AS FS
LEFT JOIN (
SELECT DISTINCT ProductSK,CategoryLabel FROM DimProduct
) AS DP
ON DP.ProductSK=FS.ProductSK
GROUP BY DP.CategoryLabel
您应该使用 INNER JOIN ON
:
SELECT CategoryLabel, SUM(F.SalesAmount)
FROM Fact_Sales AS F INNER JOIN DimProduct AS D ON F.ProductSK = D.ProductSK
GROUP BY D.CategoryLabel
我有以下 table Fact_Sales :
ProductSK DateSK SalesAmount SalesNumber
1 2019 300 150
2 2019 500 190
.....
和以下 table DimProduct:
ProductSK CategoryLabel
1 ABC
2 ABC
....
我想按类别标签计算销售额,但是当像下面这样加入时,查询结果生成笛卡尔积:
SELECT CategoryLabel, SUM(SalesAmount)
FROM Fact_Sales, DimProduct
您可以 LEFT 连接到产品的不同值 table :
SELECT DP.CategoryLabel, SUM(FS.SalesAmount)
FROM Fact_Sales AS FS
LEFT JOIN (
SELECT DISTINCT ProductSK,CategoryLabel FROM DimProduct
) AS DP
ON DP.ProductSK=FS.ProductSK
GROUP BY DP.CategoryLabel
您应该使用 INNER JOIN ON
:
SELECT CategoryLabel, SUM(F.SalesAmount)
FROM Fact_Sales AS F INNER JOIN DimProduct AS D ON F.ProductSK = D.ProductSK
GROUP BY D.CategoryLabel