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
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].
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.
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.
A PIVOT operator is limited to only one aggregate function. To perform multi aggregate pivot we need to introduce a PIVOT operator per aggregation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With