开发者

converting ID to column name and also replacing NULL with last known value

开发者 https://www.devze.com 2022-12-21 19:37 出处:网络
TABLE_A RevChangedBy ----------------------------- 1A 2B 3C TABLE_B Rev WordsID ---------------------------- 1 description_152

TABLE_A

Rev     ChangedBy
-----------------------------
1       A
2       B
3       C

TABLE_B

Rev Words      ID
----------------------------
1 description_1   52
1 history_1         54
2 description_2   52
3 history_2         54

Words column datatype is ntext.

TABLE_C

ID Name
-----------------------------
52 Description
54 History

OUTPUT

Rev ChangedBy Description        History  
-------------------------开发者_JAVA百科-----------------------
1     A   description_1      history_1
2     B   description_2      history_1
3     C   description_2      history_2

Description and History column will have the previous known values if they dont have value for that Rev no. i.e. Since for Rev no. 3 Description does not have an entry in TABLE_B hence the last known value description_2 appears in that column for Rev no. 3 in the output.


With help from following posts
PIVOT on Common Table Expression
SQL QUERY replace NULL value in a row with a value from the previous known value

I was able to come up with following query to get the desired output.

    ;WITH CTE_A AS
    (
        SELECT a.Rev, a.ChangedBy, CAST(b.Words as nvarchar(max)) as [Words],c.Name FROM Table_A AS a
        INNER JOIN Table_B AS b ON a.Rev = b.Rev
        INNER JOIN Table_C AS c ON b.FId = c.Id
    ),
    CTE_B AS
    (

    select Rev, ChangedBy, [Description], [History] from
    CTE_A
    PIVOT
    (
        MAX([Words])
        FOR [Name] in ([Description],[History])
    ) as p
    )

select Rev,ChangedBy, 
ISNULL([Description],(select top 1 [Description] from CTE_B where Rev < t.Rev and [Description] is not null order by Rev desc)),
ISNULL([History],(select top 1 [History] from CTE_B where Rev < t.Rev and [History] is not null order by Rev desc))  
from CTE_B t
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号