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

질문됨 일 년 전1688회 조회
1개 답변
0
수락된 답변

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
전문가
ZJon
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠