如何组合Power Query中两个相邻行的值?

时间:2017-05-13 15:09:43

标签: powerquery m

我有这种格式的地址列表:

|ID|AddrType|Company|FName |LName |Address
| 1|Visiting|ACME   |Willie|Coyote|Sand Rd 10
| 1|Delivery|ACME   |Road  |Runner|Sand Rd 20
| 2|Visiting|Go Nuts|Chip  |Munk  |Tree Rd 3
| 3|Visiting|In Sane|Dale  |Munk  |Tree Rd 5

仅当递送地址与访问地址不同时,才会显示递送类型地址行。 因此,每个公司ID的地址数量可能不同

我想得到这样的结果:

|ID|V_Company|V_FName|V_LName|V_Address |D_Company|D_FName|D_LName|D_Address
| 1|ACME     |Willie |Coyote |Sand Rd 10|ACME     |Road   |Runner |Sand Rd 20
| 2|Go Nuts  |Chip   |Munk   |Tree Rd 3 |Go Nuts  |Chip   |Munk   |Tree Rd 3
| 3|In Sane  |Dale   |Munk   |Tree Rd 5 |In Sane  |Dale   |Munk   |Tree Rd 5

我尝试使用此链接中描述的转置功能并失败: https://community.powerbi.com/t5/Desktop/Merge-2-rows-in-one-row/m-p/46361#M18144

我还尝试过创建自定义列,但如果下面一行的AddrType值为Delivery,则从下面的行中获取值。

= Table.AddColumn(#"Sorted columns", "D_FName", each if [AddrTyp]="Delivery" then [FName]{[Index]+1} else FName)

我使用此链接作为visdom bu的来源,但收效甚微: http://excel-inside.pro/blog/2015/11/05/absolute-and-relative-references-in-power-query/

我相信有一种简单的方法可以得到我想要的东西。我现在依靠你的经验和知识来解决它。

请帮助我!

1 个答案:

答案 0 :(得分:1)

创建一个包含第二个地址的表:在AdressType上排序AddressList(升序,因此交付将首先出现),缓冲并删除重复项。

其余代码应该是显而易见的:

查询" SecondAdresses":

let
    Source = AddressList,
    Sorted = Table.Buffer(Table.Sort(Source,{{"AddrType", Order.Ascending}})),
    SelectDistinct = Table.Distinct(Sorted, {"ID"}),
    D_Headers = Table.TransformColumnNames(SelectDistinct, each "D_"&_)
in
    D_Headers

查询"结果":

let
    Source = AddressList,
    SelectVisiting = Table.SelectRows(Source, each ([AddrType] = "Visiting")),
    RemovedAddressType = Table.RemoveColumns(SelectVisiting,{"AddrType"}),
    V_Headers = Table.TransformColumnNames(RemovedAddressType, each "V_"&_),
    Merged = Table.NestedJoin(V_Headers,{"V_ID"},SecondAddresses,{"D_ID"},"NewColumn",JoinKind.LeftOuter),
    Expanded = Table.ExpandTableColumn(Merged, "NewColumn", {"D_Company", "D_FName", "D_LName", "D_Address"}, {"D_Company", "D_FName", "D_LName", "D_Address"}),
    RenamedID = Table.RenameColumns(Expanded,{{"V_ID", "ID"}})
in
    RenamedID