MS-Access or Excel: Convert data from rows to columns, in unknown range of columns

非 Y 不嫁゛ 提交于 2021-01-29 14:58:05

问题


I have a table like this:

 **customer_id        product_id**        
  1                  1234        
  1                  1125        
  1                  6528    
  2                  5645       
  2                  5528       
  3                  4565        

And I want to make a query that will give the same information, where each consumer will have one row, and each product_id will be in a separate column, when I do not know how many columns are needed, because each consumer has made a different amount of purchases, This is the result I want:

**customer_id        First_product              Second_product              Third_product      **
  1                  1234                         1125                         6528
  2                  5645                         5528 
  3                  4565

Note this: How to concatenate text from multiple rows into a single text string in SQL server?

There he does a similar thing, but all the values are in the same column with a comma between them, I want each value to have a separate column.


回答1:


In Excel, you can do this using Power Query (available in Excel 2010+)

M-Code

let
    Source = Excel.CurrentWorkbook(){[Name="Table5"]}[Content],
    #"Grouped Rows" = Table.Group(Source, {"customer_id"}, {{"Grouped", each _, type table [customer_id=nullable number, product_id=nullable number]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Product", each Table.Column([Grouped],"product_id")),
    #"Extracted Values" = Table.TransformColumns(#"Added Custom", {"Product", each Text.Combine(List.Transform(_, Text.From), ";"), type text}),
    
    #"Split Column by Delimiter" = Table.SplitColumn(
            #"Extracted Values", "Product", 
            Splitter.SplitTextByDelimiter(";", QuoteStyle.Csv)),
    #"Removed Columns" = Table.RemoveColumns(#"Split Column by Delimiter",{"Grouped"})
in
    #"Removed Columns"




回答2:


Consider:

TRANSFORM First(Table1.product_id) AS ProdID
SELECT Table1.customer_id
FROM Table1
GROUP BY Table1.customer_id
PIVOT DCount("*","Table1","customer_id=" & [customer_id] & " AND [product_id]<" & product_id)+1;

If there is a unique record identifier field (autonumber should serve):

TRANSFORM First(Table1.product_id) AS ProdID
SELECT Table1.customer_id
FROM Table1
GROUP BY Table1.customer_id
PIVOT DCount("*","Table1","customer_id=" & [customer_id] & " AND [id]<" & id)+1;

Or use order date field instead of ID field in DCount() expression.



来源:https://stackoverflow.com/questions/64032273/ms-access-or-excel-convert-data-from-rows-to-columns-in-unknown-range-of-colum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!