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

已提問 1 年前檢視次數 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
已回答 1 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南