基于Member ID与Create Date拼接分组的多行转列需求
Data Transformation: Group & Pivot Answers by Member ID + Create Date
Got it, let's work through this data transformation task. You need to group rows by the combined key of Member ID and Create Date, then flatten multiple Answer values from the same group into separate columns (Answer and Answer 2). Let's break down solutions for both SQL and Python (Pandas), since those are the most common tools for this kind of work.
Source Data
| Row | Member ID | Create Date | Answer |
|---|---|---|---|
| 1 | 1234 | 20170101 | 20170101 |
| 2 | 1234 | 20170101 | 1 |
| 3 | 1234 | 20170201 | 20170201 |
| 4 | 7778 | 20180301 | 1 |
| 5 | 7781 | 20180201 | 2080201 |
| 6 | 7778 | 20180301 | 20180301 |
Target Output
| Row | Member ID | Create Date | Answer | Answer 2 |
|---|---|---|---|---|
| 1 | 1234 | 20170101 | 20170101 | 1 |
| 2 | 1234 | 20170201 | 20170201 | |
| 3 | 7778 | 20180301 | 1 | 20180301 |
| 4 | 7781 | 20180201 | 2080201 |
Solution 1: SQL (Works with most databases like PostgreSQL, MySQL, SQL Server)
We'll use window functions to assign a sequence number to each Answer in the same group, then use conditional aggregation to pivot those values into separate columns:
WITH ranked_answers AS ( SELECT "Member ID", "Create Date", "Answer", -- Assign a unique number to each Answer in the same (Member ID, Create Date) group ROW_NUMBER() OVER (PARTITION BY "Member ID", "Create Date" ORDER BY "Row") AS answer_seq FROM your_source_table ) SELECT -- Generate a new Row number for the final output ROW_NUMBER() OVER (ORDER BY "Member ID", "Create Date") AS "Row", "Member ID", "Create Date", -- Grab the first Answer in the group MAX(CASE WHEN answer_seq = 1 THEN "Answer" END) AS "Answer", -- Grab the second Answer (if exists) MAX(CASE WHEN answer_seq = 2 THEN "Answer" END) AS "Answer 2" FROM ranked_answers GROUP BY "Member ID", "Create Date" ORDER BY "Member ID", "Create Date";
How this works:
- The
ranked_answersCTE adds ananswer_seqcolumn that numbers each Answer in the group starting from 1, ordered by the originalRownumber. - The main query groups by
Member IDandCreate Date, then usesMAX(CASE...)to pull the first and second Answer values into their own columns. - Finally, we generate a new
Rownumber for the transformed output.
Solution 2: Python with Pandas
If you're working with data in a Python environment, Pandas makes this pivot operation straightforward:
import pandas as pd # Load your source data into a DataFrame df = pd.DataFrame({ "Row": [1, 2, 3, 4, 5, 6], "Member ID": [1234, 1234, 1234, 7778, 7781, 7778], "Create Date": [20170101, 20170101, 20170201, 20180301, 20180201, 20180301], "Answer": ["20170101", "1", "20170201", "1", "2080201", "20180301"] }) # Assign a sequence number to each Answer in the same group df["answer_seq"] = df.groupby(["Member ID", "Create Date"])["Row"].rank(method="first").astype(int) # Pivot the DataFrame to turn answer_seq into columns pivoted_df = df.pivot( index=["Member ID", "Create Date"], columns="answer_seq", values="Answer" ).reset_index() # Rename columns to match your target output pivoted_df.columns = ["Member ID", "Create Date", "Answer", "Answer 2"] # Add the Row column pivoted_df["Row"] = pivoted_df.index + 1 # Reorder columns to match the target layout pivoted_df = pivoted_df[["Row", "Member ID", "Create Date", "Answer", "Answer 2"]] # Show the result print(pivoted_df)
How this works:
- We first add an
answer_seqcolumn to number each Answer in its group, using the originalRoworder. - The
pivotmethod converts the sequence numbers into column headers, placing each Answer value in the correct column. - Finally, we clean up column names, add the new
Rownumber, and reorder columns to match your target table.
内容的提问来源于stack exchange,提问作者user9539580
相关产品推荐
相关产品推荐

