2016-03-16 51 views
0

我有2個表,加入SQL Server中有幾個數據

表1是fact_table

style sales 
ABC  100 
DEF  150 

和表2是m_product

product_code style category 
ABCS   ABC  Apparel 
ABCM   ABC  Apparel 
ABCL   ABC  Apparel 
DEF38   DEF  Shoes 
DEF39   DEF  Shoes 
DEF40   DEF  Shoes 

,我想加入這兩個表,我想要的結果是

style category sales 
ABC  Apparel 100 
DEF  Shoes  150 

創建這樣的查詢,但如果我使用SUM(銷售)和group by,結果將總結所有的銷售失敗

Select t1.style, t2.category, t1.sales 
From fact_table t1 
Inner Join m_product t2 
On t1.style = t2.style 

結果

style category sales 
ABC  Apparel 100 
ABC  Apparel 100 
ABC  Apparel 100 

。 我是否必須使用平均水平(銷售量),然後選擇分組方式,還是您有其他選擇?

我正在使用SQL Server。

感謝

回答

2

使用子查詢:

Select t1.style, t2.category, t1.sales 
From fact_table t1 
Inner Join (SELECT DISTINCT style, category FROM m_product) t2 
On t1.style = t2.style 

順便說一句,您需要更改數據庫設計的類別移動到一個單獨的表像這樣

+0

我投給說*移動的類別到一個單獨的表* –

0

也許一些:

select p.style, p.category, f.sales 
(select distinct style, category 
from m_product) p join fact_table f 
on p.style = f.style 
0

試試這個。不確定你的表格結構是否正確。如果在事實表中沒有產品代碼而不是樣式。如果有人要求您按產品計算銷售額,那麼此結構將無法回答。

Select t1.style, (select distinct t2.category from 
m_product t2 
where t1.style = t2.style) as category, t1.sales 
From fact_table t1 
0

使用DISTINCT關鍵字

Select DISTINCT t1.style, t2.category, t1.sales 
    From fact_table t1 
    Inner Join m_product t2 
    On t1.style = t2.style