سؤال

What do the SQL code look like for a simple pivoting example with a few table in sixth normal form?

Alot of people talk about how its easy and fast to pivot using 6NF tables but its really hard to find a example of this.

Lets say i have the following tables:

Table: EntryCost
EntryId
Cost

Table: EntryMonth
EntryId
Month

Table: EntryDim1
EntryId
Dim1

Table: EntryDim2
EntryId
Dim2

How would i pivot this without using MSSQL PIVOT or equivalent? Saying i wanted to aggregate Cost with dimensions down the side and months along the columns

هل كانت مفيدة؟

المحلول

I think general approach would be something like this:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top