04 August 2018 · DataFreak ·       Add to Favorites   Report

How to Pivot a table in Big Query

There are a lot of times when you have data in multiple rows and you want to pivot them to show up in a single row,


Here's a #standardSQL solution and a more general case of pivoting. In this case, we have multiple rows, and each sensor looks at a different type of property. To pivot it, we would do something like:

SELECT SensorName,
  , AVG(IF(SensorType LIKE '%altitude', Data, null)) altitude
  , AVG(IF(SensorType LIKE '%light', Data, null)) light
  , AVG(IF(SensorType LIKE '%mic', Data, null)) mic
  , AVG(IF(SensorType LIKE '%temperature', Data, null)) temperature
FROM `data-sensing-lab.io_sensor_data.SensorData`

As an alternative to AVG() you can try MAX()ANY_VALUE(), etc


posted on 04 August 2018

Read great educational content like this and a lot more !

Members get free exclusive access to content, new courses, and discounts. Signup for a free account to write a post / comment / upvote posts. Creating an account takes less than 5 seconds and you can start earning badges & points too