![](/img/trans.png)
[英]How to transfer data from wide format to long format in Excel Or SQL?
[英]Excel script or formula to transform from wide to long format, with a caveat
為了簡單起見,我會說我有這張表(原始表擴展得更寬,比方說,最多 30 個項目、價格和數量):
Date| Requester| Item1| Amount1| Price1| Item2| Amount2| Price2|
12-10| A| Shoe| 200| 30| Shirt| 40| 10|
12-10| B| Socks| 20| 10| | | |
13-10| A| | | | Gloves| 5| 3|
我正好需要這個 output:
Date| Requester| Item| Amount| Price|
12-10| A| Shoe| 200| 30|
12-10| A| Shirt| 40| 10|
12-10| B| Socks| 20| 10|
13-10| A| Gloves| 5| 3|
我已經遇到了一些在稱為“變量”的列中顯示 3 個變量的逆透視公式,但這不適合我,我想減少列數,是的,但也保留 3 個關鍵變量分成 3 列。 此外,由於原始表有數千條記錄,我希望 output 不要為空列創建不必要的行,否則它可能會崩潰或變得難以管理。 我發現的所有腳本都會為空數據創建不必要的行。 請注意,在我發布的示例中,如果項目、金額和價格數據為空,output 表不會打印不必要的行。
謝謝。
您可以使用Power Query
執行此操作,可在 Excel 2010+ 中獲得
通過 PQ 編輯器的“應用步驟”window 來更好地了解發生了什么
null
替換任何空白(因此它們將在下一步中被排除){0,0,0,1,1,1,2,2,2...}
的系列M代碼
let
Source = Excel.CurrentWorkbook(){[Name="Table5"]}[Content],
//Replace blanks with null
#"Replaced Value" = Table.ReplaceValue(Source,"",null,Replacer.ReplaceValue,Table.ColumnNames(Source)),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Replaced Value", {"Date", "Requester"}, "Attribute", "Value"),
#"Removed Columns" = Table.RemoveColumns(#"Unpivoted Other Columns",{"Attribute"}),
#"Added Index" = Table.AddIndexColumn(#"Removed Columns", "Index", 0, 1, Int64.Type),
#"Inserted Integer-Division" = Table.AddColumn(#"Added Index", "Integer-Division", each Number.IntegerDivide([Index], 3), Int64.Type),
#"Removed Columns1" = Table.RemoveColumns(#"Inserted Integer-Division",{"Index"}),
#"Grouped Rows" = Table.Group(#"Removed Columns1", {"Integer-Division"}, {{"Group", each _, type table [Date=nullable date, Requester=nullable text, Value=any, #"Integer-Division"=number]}}),
#"Removed Columns2" = Table.RemoveColumns(#"Grouped Rows",{"Integer-Division"}),
#"Added Custom" = Table.AddColumn(#"Removed Columns2", "Date", each Table.Column([Group],"Date"){0}),
#"Added Custom1" = Table.AddColumn(#"Added Custom", "Requester", each Table.Column([Group],"Requester"){0}),
#"Added Custom2" = Table.AddColumn(#"Added Custom1", "Custom", each Table.Column([Group],"Value")),
#"Extracted Values" = Table.TransformColumns(#"Added Custom2", {"Custom", each Text.Combine(List.Transform(_, Text.From), ";"), type text}),
#"Split Column by Delimiter" = Table.SplitColumn(#"Extracted Values", "Custom", Splitter.SplitTextByDelimiter(";", QuoteStyle.Csv), {"Custom.1", "Custom.2", "Custom.3"}),
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Date", type date}, {"Custom.1", type text}, {"Custom.2", Int64.Type}, {"Custom.3", Currency.Type}}),
#"Renamed Columns" = Table.RenameColumns(#"Changed Type1",{{"Custom.1", "Item"}, {"Custom.2", "Amount"}, {"Custom.3", "Price"}}),
#"Removed Columns3" = Table.RemoveColumns(#"Renamed Columns",{"Group"})
in
#"Removed Columns3"
您應該能夠向任何行添加更多的“三元組”數據; 或更多行; 無需更改代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.