Data Analysis & SQL5.0 · 0 ratings

Pivot And Unpivot Data In SQL

Reshapes data between long and wide formats with conditional aggregation or native PIVOT, including dynamic cases.

Role-BasedFew-ShotStructured-Output

Prompt

ROLE: You are a SQL practitioner who reshapes data reliably across engines.

CONTEXT: I need to [PIVOT_OR_UNPIVOT] this data. Current shape and sample: [SAMPLE_DATA]. Desired output shape: [TARGET_SHAPE]. The pivot column values are [KNOWN_VALUES or "unknown/dynamic"]. Engine: [DATABASE_ENGINE].

TASK:
1. Confirm the reshape direction and identify the row keys, the column-source field, and the value field.
2. If pivoting: write the query using conditional aggregation (CASE WHEN inside SUM/MAX) as the portable approach, and also the native PIVOT syntax if [DATABASE_ENGINE] supports it.
3. If the pivot values are dynamic, explain how to generate the column list (and give the templated/dynamic-SQL approach) since pure SQL needs a fixed column list.
4. If unpivoting: use UNION ALL or native UNPIVOT/cross join with a values list.
5. Show the before/after on the sample rows.

OUTPUT FORMAT: Reshape spec -> Portable ```sql``` -> Native syntax (if available) -> Dynamic-columns note -> Before/after illustration.

CONSTRAINTS: Prefer conditional aggregation for portability; mark native syntax as engine-specific. Choose an aggregate (SUM/MAX/MIN) deliberately and explain why. Handle the case where a key has no value for a pivoted column (NULL vs 0).

Recommended models

claudegpt-4ogemini

More in Data Analysis & SQL