将列拆分为新架构

时间:2017-06-02 05:53:56

标签: powerquery

作为Power Query和M的新手,我试图使用分隔符值拆分列,但也使用前缀到给定的模式中。

原始表值如下所示:

20170101T1231_Name_A#1234_C#AB DEF_D#Comment
20170203T1543_A#11111_B#COL2_C#XYZ QRSTUV_D#Comment

我可以使用_作为分隔符将列拆分为多个列,但是所需的结果是将每个带前缀的#值放在它们自己的列中。

DATE&TIME     | Text | A#    | B#   | C#         | D#
20170101T1231 | Name | 1234  |      | AB DEF     | Comment
20170203T1543 |      | 11111 | COL2 | XYZ QRSTUV | Comment

1 个答案:

答案 0 :(得分:1)

这段代码可以解决问题:

let
    Source = Table1,
    #"Split Column by Position" = Table.SplitColumn(Source, "Column1", Splitter.SplitTextByPositions({0, 13}, false), {"Column1.1", "Column1.2"}),
    #"Changed Type" = Table.TransformColumnTypes(#"Split Column by Position",{{"Column1.1", type datetime}, {"Column1.2", type text}}),
    Splitted = Table.TransformColumns(#"Changed Type",{{"Column1.2", each Text.Split(_,"_")}}),
    #"Added Index" = Table.AddIndexColumn(Splitted, "Index", 0, 1),
    #"Expanded Column1.2" = Table.ExpandListColumn(#"Added Index", "Column1.2"),
    #"Filtered Rows" = Table.SelectRows(#"Expanded Column1.2", each [Column1.2] <> null and [Column1.2] <> ""),
    AddedTextLabel = Table.TransformColumns(#"Filtered Rows",{{"Column1.2", each if Text.Contains(_,"#") then _ else " Text#"&_}}),
    #"Inserted Text After Delimiter" = Table.AddColumn(AddedTextLabel, "Text After Delimiter", each Text.AfterDelimiter([Column1.2], "#", 0), type text),
    #"Trimmed Text1" = Table.TransformColumns(#"Inserted Text After Delimiter",{{"Column1.2", each Text.Start(_,1+Text.PositionOf(_,"#"))}}),
    #"Pivoted Column" = Table.Pivot(#"Trimmed Text1", List.Sort(List.Distinct(#"Trimmed Text1"[Column1.2])), "Column1.2", "Text After Delimiter"),
    #"Renamed Columns" = Table.RenameColumns(#"Pivoted Column",{{"Column1.1", "DATE&TIME"}, {" Text#", "Text"}}),
    #"Removed Columns" = Table.RemoveColumns(#"Renamed Columns",{"Index"})
in
    #"Removed Columns"