简体   繁体   中英

SQL Server - Slowly Changing dimension join

I have a fact table and employee "tier" table, let's say.

So the fact table looks sorta like

employee_id    call    date
Mark           1       1-1-2017
Mark           2       1-2-2017
John           3       1-2-2017

Then there needs to be a data structure for 'tier level' - a slowly changing dimension table. I want to keep this simple -- I can change the structure of this table to whatever, but for now I've created it as such.

employee_id   tier1_start ... tier2_start ... tier3_start
Mark           5-1-2016
John           6-1-2016         8-1-2016
Lucy           6-1-2016                       10-1-2016

Two important notes. This table sort of operates under the assumption that a promotion will only occur once - aka no demotions and repromotions will occur. Also, it's possible one can jump from tier 1 to tier 3.

I was trying to come up with the best possible query for coming up with a 'tier' dimension (denormalization) for the fact table.

For instance, I want to see the Tier 1 metrics for February, or the Tier 2 metrics for February. Obviously the historically-changing tier dimension must be linked.

The clumsiest way I can think of doing this for now ... is simply joining the fact table on the tier table using employee_id.

Then, doing an even clumsier case statement:

case
when isnull(tier3_start,'0') < date then 'T3'
when isnull(tier2_start, '0') < date then 'T2'
when isnull(tier1_start, '0') < date then 'T1'
else 'other'
end as tier_level

Yes, as you can see this is very clumsy. I'm thinking maybe I need to change the structure of this a bit.

You're probably better off splitting your tier table in two.

So have a Tier table like this:

TierID    Tier
------------------
1         Tier 1
2         Tier 2
3         Tier 3

And an EmployeeTier table:

ID    EmpID    TierID    TierDate
---------------------------------------
1     1        1         Jun 1, 2016
2     1        3         Oct 2, 2016
3     2        1         Jul 10, 2016
4     2        2         Nov 11, 2016

Now you can query the EmployeeTier table and filter on the TierID you're looking for.

This also gives you the ability to promote/demote multiple times. You simply filter by the employee and sort by date to find the current tier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM