简体   繁体   中英

Populate fact table SQL server

I am trying to set the IDs of a fact table to be the same as one my dimension tables.

PRICE_TABLE             FACT_TABLE
P_ID                    P_ID
1                       0    
2                       0
3                       0
...                     ....

Does anyone have any suggestions for a good approach on this?

UPDATE FACT_TABLE 
    SET FACT_TABLE.P_ID = PRICE_TABLE.P_ID 
    /* cannot seem to get a join here working */

I have tried joining the tables, but as there is no common values I cant seem to get it to work.

you can use update from select:

UPDATE ft
SET ft.P_ID = pt.P_ID
FROM FACT_TABLE ft
LEFT JOIN PRICE_TABLE pt ON (pt.SomeField = ft.AnotherField) -- some join condition should be here

also you can use insert into select, like:

TRUNCATE TABLE FACT_TABLE; -- it will remove all data from your table
GO;
INSERT INTO FACT_TABLE (P_ID, other fields...) 
SELECT P_ID, other fields FROM PRICE_TABLE

You could use ROW_NUMBER to join records from both tables like this:

;WITH FACT_TABLE_RN AS (
   SELECT P_ID, 
          ROW_NUMBER() OVER (ORDER BY P_ID) AS rn
   FROM FACT_TABLE
), PRICE_TABLE_RN AS (
   SELECT P_ID, 
          ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
   FROM PRICE_TABLE
)
UPDATE ft
SET P_ID = pt.P_ID
FROM FACT_TABLE_RN AS ft
JOIN PRICE_TABLE_RN AS pt ON pt.rn = ft.rn

For the moment, I can propose to you this. I guess we can find another way without the temp table. But it should do the work, for the moment.

with prices as
(
    select
        id = row_number() over(),
        P_ID
    from PRICE_TABLE
),
facts as
(
    select
        id = row_number() over()
        -- facts fieds you want
    from FACT_TABLE
)
select
    P_ID = prices.P_ID
    -- facts fieds you want
into #facts
from facts
    join prices on prices.id = facts.id

delete FACT_TABLE

insert FACT_TABLE
(
    P_ID
    -- facts fieds you want
)
select
    P_ID
    -- facts fieds you want
from #facts

drop table #facts

You may have to uncheck the constraint on FACT_TABLE.P_ID, to use this script


If I understand well, your FACT_TABLE contains only your P_ID, which comes from PRICE_TABLE. Why the need to use this FACT_TABLE instead of PRICE_TABLE directly ? Why do you not create your FACT_TABLE with insert/select instead of trying to update the P_ID field of FACT_TABLE ?

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