Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

teradata sql pivot multiple occurrences into additional columns

I have something like this:

ID      Result
1       value1
2       value1
2       value2
3       value1
4       value1
4       value2
4       value3

And I'd like to return something like this:

ID      Result1      Result2      Result3
1       value1
2       value1       value2
3       value1
4       value1       value2       value3

I've searched on pivots and concats and breaks and I just can't find a simple, sensible solution.

TIA

like image 618
user2820576 Avatar asked Sep 26 '13 17:09

user2820576


People also ask

How do I aggregate on more than one column within a PIVOT?

On SQL Server pivot query using UNION ALL of two pivot queries multiple aggregations can be implemented easily. ;WITH PivotData AS ( SELECT [CustomerID], -- grouping column [ShipMethodID], -- spreading column [ShipMethodID]+1000 as [ShipMethodID2], freight -- aggregation column ,CurrencyRateID FROM [Sales].

Can we PIVOT on multiple columns?

Add an Additional Row or Column Field Click any cell in the PivotTable. The PivotTable Fields pane appears. You can also turn on the PivotTable Fields pane by clicking the Field List button on the Analyze tab. Click and drag a field to the Rows or Columns area.

Can we use multiple aggregate functions in PIVOT in SQL?

It is a common question to get the output of at least two aggregate functions in the SQL pivot table columns. Of course it is not possible to combine two different values resulting from two aggregate functions only in a single column.

Is it possible to have multiple pivots using the same PIVOT column using SQL Server?

A PIVOT operator is limited to only one aggregate function. To perform multi aggregate pivot we need to introduce a PIVOT operator per aggregation.


1 Answers

Unfortunately Teradata doesn't have a PIVOT function but you can use an aggregate function with a CASE expression to get the result.

select id,
    max(case when seq =1 then result end) result1,
    max(case when seq =2 then result end) result2,
    max(case when seq =3 then result end) result3
from
(
    select id, res, row_number() over(partition by id order by result) seq
    from yourtable
) d
group by id
order by id;

If you have more values for each ID, then you can add more CASE expressions.

like image 95
Taryn Avatar answered Oct 20 '22 00:10

Taryn