如何用SQL的PIVOT无聚合转换2×2表?现有代码报错求排查
Fixing Your SQL PIVOT Query
Let’s break down the issues in your code and fix them step by step:
Key Errors in Your Code
- Missing Aggregate Function: The
PIVOTclause requires an aggregate function (likeSUM,MAX,MIN, orCOUNT) to summarize the values you want to pivot. Your code usesnumber(123), which is invalid syntax—this isn’t a valid aggregate operation. - Incorrect SELECT Column: After pivoting, the
namecolumn won’t exist in the resultingpivot_tablebecause you’re pivoting on thenamecolumn itself. You shouldn’t include it in your finalSELECTlist. - Unclear 2x2 Table Structure: Your current query only targets one name (
Andy), which won’t produce a 2x2 table. You’ll need to include a second row dimension (like a group/category column) and a second name to get the desired layout.
Corrected Basic Pivot (Single Column)
If you just want to pivot the number value for Andy into a column (assuming each name has one unique number), use this:
SELECT Andy FROM ( SELECT name, number FROM Customer ) t PIVOT ( MAX(number) -- Use MAX since each name has one value; adjust to SUM/COUNT if needed FOR name IN (Andy) ) AS pivot_table;
Example for 2×2 Table
Let’s assume your Customer table has an additional column (e.g., group_id) that creates the row dimension (values 1 and 2), and you want to pivot two names (Andy and Bob) as columns. Here’s how to get a 2x2 table:
Sample Customer Table Data
| group_id | name | number |
|---|---|---|
| 1 | Andy | 123 |
| 1 | Bob | 456 |
| 2 | Andy | 789 |
| 2 | Bob | 012 |
Pivot Query for 2×2 Result
SELECT group_id, Andy, Bob FROM ( SELECT group_id, name, number FROM Customer ) t PIVOT ( MAX(number) FOR name IN (Andy, Bob) ) AS pivot_table;
Resulting 2×2 Table
| group_id | Andy | Bob |
|---|---|---|
| 1 | 123 | 456 |
| 2 | 789 | 12 |
Notes
- Adjust the aggregate function (
MAX,SUM, etc.) based on your data: useSUMif you need to add up numbers for a name,COUNTif you need to count entries, etc. - If your
numbercolumn has NULLs, the aggregate function will handle them appropriately (e.g.,MAXignores NULLs).
内容的提问来源于stack exchange,提问作者ella widya
相关产品推荐
相关产品推荐

