Can someone show me how to pivot in Athena SQL?

0

Hi all,

I'm trying to pivot a table in SQL but I don't know how to. I've got three colomns: day, openinghour and closinghour. Sometimes one day exicsts two times. For example: day openinghour closinghour monday 09.00 12.00 monday 13.00 17.00

Now I want to pivot the coloms in a way that the colomn name stands for the day and the row gives the specific information about the openinghours. For example: monday tuesday wednesday 09.00 - 12.00 09.00 - 12.00 12.00 - 17.00 13.00 - 16.00Enter image description here

I've added a picture of the data

asked a year ago1641 views
1 Answer
0
Accepted Answer

Greetings

Amazon Athena uses Presto SQL, which doesn't have a native PIVOT function. However, you can still achieve the desired result using conditional aggregation. Here's an example query to pivot your table based on the given data structure:

SELECT
  MAX(CASE WHEN day = 'monday' THEN CONCAT(openinghour, ' - ', closinghour) END) AS monday,
  MAX(CASE WHEN day = 'tuesday' THEN CONCAT(openinghour, ' - ', closinghour) END) AS tuesday,
  MAX(CASE WHEN day = 'wednesday' THEN CONCAT(openinghour, ' - ', closinghour) END) AS wednesday
FROM
  (SELECT day, openinghour, closinghour, ROW_NUMBER() OVER (PARTITION BY day ORDER BY openinghour) AS row_num
   FROM your_table) subquery
GROUP BY row_num;

Replace your_table with the actual name of your table in Athena.

This query first numbers the rows for each day using ROW_NUMBER() function, and then pivots the table by aggregating the rows based on the row_num column using MAX and CASE expressions. The output will display opening and closing hours for each day in separate columns, as requested.

Please let me know if I answered your question

AWS
EXPERT
ZJon
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions