有趣的问题。经过几次试验,我设法在一个查询中做到了。
询问:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("ZY49D4MgEIb/C7MLYL9m07GNadwMw9UwmKLXACb67z1sbaAMR9477rk8bcuafmAF45zTW+ux6w0FSVWB6SYDHm34p2r07J+IL4pHpooUfUxG74sVDm9wjpIInYUFRwrnDLqj19+LYfNqwW1Hyo/LNg7MDewSGiFiyfJfUqSSp5zdLUViKWPLS05FmjLWPPw0JVNqBQ==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Name = _t, Record = _t, Item.1 = _t, Value.1 = _t, Item.2 = _t, Value.2 = _t, Item.3 = _t, Value.3 = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Name", type text}, {"Record", Int64.Type}, {"Item.1", type text}, {"Value.1", Int64.Type}, {"Item.2", type text}, {"Value.2", Int64.Type}, {"Item.3", type text}, {"Value.3", Int64.Type}}),
#"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Name", "Record", "Value.1", "Value.2", "Value.3"}, "Attribute", "Value"),
#"Renamed Columns" = Table.RenameColumns(#"Unpivoted Columns",{{"Attribute", "ItemKey"}, {"Value", "Item"}}),
#"Unpivoted Columns1" = Table.UnpivotOtherColumns(#"Renamed Columns", {"Name", "Record", "ItemKey", "Item"}, "Attribute", "Value"),
#"Renamed Columns1" = Table.RenameColumns(#"Unpivoted Columns1",{{"Attribute", "ValueKey"}}),
#"Filtered Rows" = Table.SelectRows(#"Renamed Columns1", each Text.EndsWith([ItemKey], Text.End([ValueKey], 1))),
#"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"ItemKey", "ValueKey"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Item]), "Item", "Value", List.Sum)
in
#"Pivoted Column"
结果:
一点解释:
- 取消透视所有项目列
- Unpivot 所有值列(所以在这里它将创建 nxn 行记录)
- 过滤 ItemKey 与 ValueKey 匹配的记录(例如 Item.1 = Value.1 等)
- 删除 ItemKey 和 ValueKey 列
- 将项目列作为标题,将值作为值
不是最好的解决方案,因为它会创建额外的记录,但涉及的手动工作要少得多,这应该可以解决您的问题。
PS #"Filtered Rows" 包含一些 UI 中不可用的内置函数,如果您的实际数据中每条记录的项值对超过 9 个,您可能需要对其进行自定义。(因为我只比较键的最后一个字符)