
答案1
在 Power Query 中,您可以透視 TAG 列,其中 VALUE 列作為值 和no aggregation
。
但是,如果您僅對資料集執行此操作,則會傳回錯誤值,因為同一樞軸值有多個條目。
可以透過新增索引列來避免這種情況,該列會按順序對每個單獨的標籤條目進行編號。
為了做到這一點,並且還允許標籤不總是處於相同的順序,您可以
- 按標籤分組
- 為每個子表新增一個索引列
- 展開表格
- 以 TAG 為中心,不進行聚合
- 刪除索引列
在下面的程式碼中,檢查註釋和應用步驟以更好地理解。
如果此方法在您的資料集上太慢,則可以發布一個自訂函數,該函數可以執行得更快。
let
//replace next lines to reflect your actual data source
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"TAG", type text}, {"VALUE", type text}}),
//Group By Tage
#"Grouped Rows" = Table.Group(#"Changed Type", {"TAG"}, {
//add an Index column to each subtable
{"with Index", each Table.AddIndexColumn(_,"Index",0,1), type table [TAG=nullable text, VALUE=nullable text, Index=Int64.Type]}}),
//Expand the sub tables
#"Expanded with Index" = Table.ExpandTableColumn(#"Grouped Rows", "with Index", {"VALUE", "Index"}),
//Pivot with no aggregation
#"Pivoted Column" = Table.Pivot(#"Expanded with Index", List.Distinct(#"Expanded with Index"[TAG]), "TAG", "VALUE"),
//Remove the Index column
#"Removed Columns" = Table.RemoveColumns(#"Pivoted Column",{"Index"})
in
#"Removed Columns"
編輯以顯示用於執行非聚合樞軸的自訂函數
自訂功能
貼上到空白查詢中並按照程式碼註解中的方式重新命名
//credit: Cam Wallace https://www.dingbatdata.com/2018/03/08/non-aggregate-pivot-with-multiple-rows-in-powerquery/
//Rename: fnPivotAll
(Source as table,
ColToPivot as text,
ColForValues as text)=>
let
PivotColNames = List.Buffer(List.Distinct(Table.Column(Source,ColToPivot))),
#"Pivoted Column" = Table.Pivot(Source, PivotColNames, ColToPivot, ColForValues, each _),
TableFromRecordOfLists = (rec as record, fieldnames as list) =>
let
PartialRecord = Record.SelectFields(rec,fieldnames),
RecordToList = Record.ToList(PartialRecord),
Table = Table.FromColumns(RecordToList,fieldnames)
in
Table,
#"Added Custom" = Table.AddColumn(#"Pivoted Column", "Values", each TableFromRecordOfLists(_,PivotColNames)),
#"Removed Other Columns" = Table.RemoveColumns(#"Added Custom",PivotColNames),
#"Expanded Values" = Table.ExpandTableColumn(#"Removed Other Columns", "Values", PivotColNames)
in
#"Expanded Values"
主要程式碼
let
//replace next lines to reflect your actual data source
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"TAG", type text}, {"VALUE", type text}}),
//call custom pivot function
pivot = fnPivotAll(#"Changed Type","TAG","VALUE")
in
pivot