Search code examples
google-bigquery

Trim a decimal to 2 places Bigquery


I am currently running a query that runs a sum function and also divides this number. Currently I get values like 0.0904246741698848, and 1.6419814808335567. I want these decimals to be trimmed to 2 spaces past the decimal point. Their schema is a float. Here is my code. Thanks for the help.

#standardSQL
SELECT
  Serial,
  MAX(createdAt) AS Latest_Use,
  SUM(ConnectionTime/3600) as Total_Hours,
  COUNT(DISTINCT DeviceID) AS Devices_Connected
FROM `dataworks-356fa.FirebaseArchive.Firebase_ConnectionInfo`
WHERE PeripheralType = 1 or PeripheralType = 2 or PeripheralType = 12
GROUP BY Serial
ORDER BY Latest_Use DESC

Solution

  • #standardSQL
    WITH `data` AS (
      SELECT 0.0904246741698848  AS val UNION ALL
      SELECT 1.6419814808335567 
    )
    SELECT val, ROUND(val, 2) AS rounded_val
    FROM `data`   
    

    for example, assuming your want apply this to your Total_Hours column :

    #standardSQL
    SELECT
      Serial,
      MAX(createdAt) AS Latest_Use,
      ROUND(SUM(ConnectionTime/3600),2) AS Total_Hours,
      COUNT(DISTINCT DeviceID) AS Devices_Connected
    FROM `dataworks-356fa.FirebaseArchive.Firebase_ConnectionInfo`
    WHERE PeripheralType = 1 OR PeripheralType = 2 OR PeripheralType = 12
    GROUP BY Serial
    ORDER BY Latest_Use DESC