Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

categories - Google Sheets Hierarchical Subcategory Expansion

Problem Statement:

I have a list of bank transactions with an amount and a category.

I have categories defined as a string which can contain any number of : characters. The : character indicates a sub category. For example expenses Household contains all household expenses and Household : Utilities indicates the subcatogy Utiltities within houshold.

I can groupby the category and take the sum to get expenses within a specific subcategory. For example I can get the total spent on Household : Utilities or Household : Rent. But doing a groupby sum will not give me a Household entry which is the sum of the Utilities and Rent Subcategories.

I wish to be able to expand these sub category and parent category sums in in a Hierarchical way so that I have a comprehensive list. E.g If I have a transaction with Household : Utilties : Water for $10, and a transaction with Household : Utilities : Electricity for $15 I want the result to be

  • Household .............................. $ 25
  • Household : Utilities .................. $ 25
  • Household : Utilities : Water .......... $ 10
  • Household : Utilities : Electricity .... $ 15

This is a link to an example spreadsheet.

https://docs.google.com/spreadsheets/d/14URPJ4fWl6id9z0-AI1hxNClo-10gotKdMSXnuehNVI/edit?usp=sharing

I can get simple summary of category vs sum using a query() and groupby but this will not expand to parent categories.

I can do this in python, But am having difficulty getting my head around how I would do this in a spreadsheet. Does anyone have any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try:

=ARRAYFORMULA(QUERY({A5:B; 
 SPLIT(FLATTEN(IFERROR(REGEXREPLACE(REGEXREPLACE(IF(
 IFERROR(SPLIT(A5:A, ":"))="",,A5:A),
 IFERROR(SPLIT(A5:A, ":")), ), " :$| ::.+|^:.+", ))&"×"&B5:B), "×")}, 
 "select Col1,sum(Col2)
  where Col2 is not null
  group by Col1
  order by Col1
  label Col1'Category',sum(Col2)'Quantity'"))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...