How to combine 2 rows into single row in teradata?

by muriel.schmidt , in category: MySQL , 5 months ago

How to combine 2 rows into single row in teradata?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 5 months ago

@muriel.schmidt 

One way to combine 2 rows into a single row in Teradata is by using the PIVOT function. Here is an example:


If we have a table called "orders" with the following data:


order_id | product_id | order_date


1 | 100 | 2022-01-01


1 | 200 | 2022-01-01


We can combine the two rows for order_id = 1 into a single row like this:


SELECT order_id, max(case when rn = 1 then product_id end) as product_id_1, max(case when rn = 1 then order_date end) as order_date_1, max(case when rn = 2 then product_id end) as product_id_2, max(case when rn = 2 then order_date end) as order_date_2 FROM (SELECT order_id, product_id, order_date, row_number() over (partition by order_id order by product_id) as rn FROM orders) as sub GROUP BY order_id;


This query uses the row_number() function to assign a rank to each row within the partition, and then uses the max() function with a conditional to pivot the data into 2 columns for product_id and order_date.


This query will result in a single row for order_id = 1 with the data from the 2 original rows combined into separate columns.

Related Threads:

How to get 2 distinct rows from 1 row with 3 tables in sql oracle?
How to insert excel rows into teradata table?
How to delete single row in pivot table with laravel?
How to add values in single column of multiple rows in postgresql
How to combine three variables into a date (mm/dd/yyyy) in teradata?
How to check if database row exist in laravel?