简体   繁体   中英

Inserting from another table with conditions for a column

I'm trying to insert all the data from my submit table into my fact table. All the fields line up except for the status column. The status table needs to be filled with a status based on the dates. I have the rules that I need for that, but I'm not sure where I should put that logic or even how to do it. Any help is appreciated.

Insert into dbo.FactSubmit
(
    ProjectKey,
    DueFromSubKey,
    SentToKey,
    DueFromArcKey,
    ReceivedDateKey,
    [Description],
            Status

)
Select 
    dp.ProjectKey,
    CONVERT(int, Convert(varchar, s.Due_From_Sub ,112)),
    CONVERT(int, Convert(varchar,s.Sent_To, 112)),
    CONVERT(int, Convert(varchar,s.Due_From_Arc, 112)),
    CONVERT(int, Convert(varchar,s.ReceivedDate, 112)),
    s.Item_Description
From stg.Submit s
INNER JOIN dbo.DimProject dp
    ON s.ProjectID = dp.ProjectID
INNER JOIN stg.Project sp
    ON sp.ProjectID = dp.ProjectID

Something like this should be suitable for what you're doing. "Case" statements are a good approach for select statements like that.

You do the desired select as necessary, assure the columns match up and you are able to insert them

SELECT ..., 'Status' = CASE               --selecting what columns
     WHEN SomeColumn = 50 THEN 'Status1'  --this sets the logic 
     WHEN SomeColumn = 51 THEN 'Status2'  --for your case statement
     ELSE 'DefaultStatusValue'
  END
FROM stg.Submit s
INNER JOIN dbo.DimProject dp
ON s.ProjectID = dp.ProjectID
INNER JOIN stg.Project sp
ON sp.ProjectID = dp.ProjectID),

Referencing another StackQuestion .

MSDN can help too

EDIT: The 'Status' in quotes is saying what you want the new column name to be, and the "Case" statement handles what value will be selected for each row based on the logic there.

You either want a where clause:

insert into table2
(f1, f2, etc)
select f1, f2, etc
from table1
WHERE YOUR CONDITIONS ARE MET

or a case construct

insert into table2
(f1, f2)
select f1
, CASE WHEN A CONDITION IS MET THEN VALUE1 ELSE VALUE2  END

or both

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