How to Transpose Rows to Column (Pivot) in Bigquery

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,

Solution:

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:

#standardSQL
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`
GROUP BY 1

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

DataFreak

posted on 04 Aug 18

Enjoy great content like this and a lot more !

Signup for a free account to write a post / comment / upvote posts. Its simple and takes less than 5 seconds