I need to build a type 2 dimension table to store price changes for various products. In the source data, there are two tables I can pull from. One has the current price of each product, and one has the price change history for each product. Prices for some products change more than others, and if a product's price has never changed, it won't have a record in the price change table at all.
Given the following current price table:
PRODUCT_ID CURRENT_PRICE
---------- -------------
ABC123 250
DEF456 200
GHI789 325
And product price history table:
PRODUCT_ID OLD_PRICE NEW_PRICE CHANGE_DATE
---------- --------- --------- -----------
ABC123 275 250 1/1/2016
DEF456 250 225 6/1/2015
DEF456 225 200 1/1/2016
What SQL could I run to populate a type 2 dimension as follows:
PRODUCT_ID PRODUCT_PRICE VALID_FROM VALID_TO CURRENT_PRICE_INDICATOR
---------- ------------- ---------- -------- ----------------------
ABC123 275 1/1/1900 12/31/2015 N
ABC123 250 1/1/2016 12/31/9999 Y
DEF456 250 1/1/1900 5/31/2015 N
DEF456 225 6/1/2015 12/31/2015 N
DEF456 200 1/1/2016 12/31/9999 Y
GHI789 325 1/1/1900 12/31/9999 Y
2条答案
按热度按时间lx0bsm1f1#
I think it is something like this:
The result:
6vl6ewon2#
Your end-state is a typical type 2 Slowly Changing Dimension. The Price history table is a little bit of a red herring here in that the NEW_PRICE should be ignored. Simply write that data in an initial load into your dimension table with something like:
From then on you can use something akin to the merge statement below (Can't validate syntax at this moment) to merge from the source table into the destination table.
More information on slowly changing dimensions and how to handle them can be found on the Kimball Group website . After all, Ralph Kimball did invent them :)