0

I'm trying to pivot unique column values into columns and I can't figure out how to do it.

I have the following table:

ID      Model
1       100
1       100
1       200
1       200
1       200
2       100
2       100
2       100
2       300
2       300
3       100
3       100
3       200
3       200

And this is my desired output:

ID      100      200      300
1       2        3        0
1       2        3        0       
1       2        3        0      
1       2        3        0       
1       2        3        0       
2       3        0        2    
2       3        0        2       
2       3        0        2       
2       3        0        2       
2       3        0        2       
3       2        2        0      
3       2        2        0       
3       2        2        0       
3       2        2        0

So I essentially want the values for the new columns to be the count of unique values by ID number in the original Model column. I'm also want to filter by records where the values in STATUS equal A, P, and F. I have over 100 unique values in the Model column, so I'd prefer not to do this using CASE statements.

I tried performing this using dynamic SQL, but I was getting the following error:

[Teradata Database] [3706] Syntax error: expected something between ')' and the 'ORDER' keyword.

Here is my code:

-- create a string containing the dynamic SQL query
WITH unique_models AS (
  SELECT DISTINCT MODEL
  FROM table_name
  WHERE AC_STATUS IN ('ACTIVE', 'PARKED', 'FUTURE')
),
dynamic_sql AS (
  SELECT 
    'SELECT 
      ID, 
      ' ||
      TRIM(TRAILING ',' FROM (XMLAGG(
         ' SUM(CASE WHEN MODEL = ''' || MODEL || ''' THEN 1 ELSE 0 END) AS ' || MODEL || '_Count,'
       ) ORDER BY MODEL ASC)) || 
      ' FROM table_name 
        WHERE STATUS IN (''A'', ''P'', ''F'')
        GROUP BY ID;'
    AS sql_query
  FROM unique_models
)
SELECT sql_query
FROM dynamic_sql;
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
  • 1
    Does this answer your question? [Accomplish pivot in teradata sql](https://stackoverflow.com/questions/22335854/accomplish-pivot-in-teradata-sql) – nbk Mar 17 '23 at 00:25
  • 1
    As far as the dynamic SQL: The `)` before the ORDER BY clause is misplaced; the ORDER BY is part of XML_AGG so there should be `)))` after the ORDER BY – Fred Mar 17 '23 at 00:41

0 Answers0