2013-10-14 75 views
0

SQL代碼對於具有第六範式表中幾個表的簡單示例有什麼作用?SQL如何關聯6NF表

很多人都在談論如何使用6NF表來輕鬆快速地旋轉,但很難找到這樣的例子。

可以說我有如下表:

Table: EntryCost 
EntryId 
Cost 

Table: EntryMonth 
EntryId 
Month 

Table: EntryDim1 
EntryId 
Dim1 

Table: EntryDim2 
EntryId 
Dim2 

我怎麼會轉動這不使用MSSQL PIVOT或等同?說我想總成本與尺寸往下方和幾個月沿着列

回答

0

我覺得一般的做法是這樣的:

select 
    D1.Dim1, D2.Dim2, 
    sum(case when M.Month = 1 then C.Cost end) as [1], 
    sum(case when M.Month = 2 then C.Cost end) as [2], 
    sum(case when M.Month = 3 then C.Cost end) as [3], 
    sum(case when M.Month = 4 then C.Cost end) as [4], 
    sum(case when M.Month = 5 then C.Cost end) as [5], 
    sum(case when M.Month = 6 then C.Cost end) as [5], 
    sum(case when M.Month = 7 then C.Cost end) as [7], 
    sum(case when M.Month = 8 then C.Cost end) as [8], 
    sum(case when M.Month = 9 then C.Cost end) as [9], 
    sum(case when M.Month = 10 then C.Cost end) as [10], 
    sum(case when M.Month = 11 then C.Cost end) as [11], 
    sum(case when M.Month = 12 then C.Cost end) as [12] 
from EntryCost as C 
    left outer join EntryMonth as M on M.EntryID = C.EntryID 
    left outer join EntryDim1 as D1 on D1.EntryID = C.EntryID 
    left outer join EntryDim2 as D2 on D2.EntryID = C.EntryID 
group by D1.Dim1, D2.Dim2 
+0

好還我在想什麼,但不確定,如果我錯過了什麼,即時通訊不熟練SQL。我會讓這個問題開放一段時間讓其他人蔘與進來。 – CodeMonkey

+0

@Jepa我會說讓我們等待其他答案。也可以在sum中使用子查詢(因爲6NF),但我不認爲這是更好的方法 –