How do I CAST AS DECIMAL in postgresql?
Asked Answered
O

3

9

The Percent_Failure in the query below is giving results as either 1.00 or 0.00. Can anyone help me understand why it's not giving me the actual decimal?

SELECT
    sf.hierarchy_name AS Hierarchy_Name,
    cl.cmh_id AS CMH_ID,
    cl.facility_name AS Clinic_Name,
    sf.billing_city AS City,
    sf.billing_state_code AS State,
    cl.num_types AS Num_Device_Dypes,
    cl.num_ssids AS Num_SSIDs,
    SUM(CAST(CASE WHEN (d.mdm_client_version NOT LIKE '1.14%' AND d.type = 'Wallboard')
        OR (d.mdm_client_version NOT LIKE '1.14%' AND d.type = 'Tablet')
        OR (d.mdm_client_version NOT LIKE '1.14%' AND d.type = 'AndroidMediaPlayer')
        OR (d.mdm_client_version NOT LIKE '1.14%' AND d.type = 'InfusionRoomTablet') THEN 1 ELSE 0 END AS INTEGER))  AS Non_Updated, 
    COUNT(d.asset_id) AS Total_Devices
    CAST((Non_Updated) / (Total_Devices) AS DECIMAL (5,4)) AS Percent_Failure
FROM 
    (SELECT id, clinic_table_id, type, asset_id, mdm_client_version, device_apk_version, ssid
    FROM mdm.devices) d
JOIN 
    (SELECT a.id, a.cmh_id, a.facility_name, COUNT(DISTINCT b.ssid) AS num_ssids, COUNT(DISTINCT b.type) AS num_types
    FROM mdm.clinics a
        JOIN 
            (SELECT *
            FROM mdm.devices
            WHERE status = 'Active'
            AND last_seen_at >= (CURRENT_DATE - 2)
            AND installed_date <= (CURRENT_DATE - 3)) b 
            ON a.id = b.clinic_table_id
    GROUP BY 1,2,3) cl
    ON d.clinic_table_id = cl.id
JOIN
    (SELECT x.cmh_id, x.hierarchy_group, x.hierarchy_name, x.billing_city, x.billing_state_code
    FROM salesforce.accounts x) sf
    ON sf.cmh_id = cl.cmh_id  
GROUP BY 1,2,3,4,5,6,7
ORDER BY 10 DESC;
Outfield answered 1/2, 2019 at 21:35 Comment(0)
T
19

Integer / Integer = Integer. So, you need to cast it before you do the division:

cast (Non_Updated as decimal) / Total_Devices AS Percent_Failure

or shorthand:

Non_Updated::decimal / Total_Devices AS Percent_Failure

I've seen other cute implementations, such as

Non_Updated * 1.0 / Total_Devices AS Percent_Failure

Also, are you sure that total_devices is always non-zero? If not, be sure to handle that.

Telugu answered 1/2, 2019 at 21:44 Comment(0)
G
3

Try individually cast numerator or denominator as decimal, otherwise the result of the division is considered to be integers.

So you can use :

Non_Updated / CAST(Total_Devices AS DECIMAL) 

or

CAST ( Non_Updated AS DECIMAL ) / Total_Devices
Gorgeous answered 1/2, 2019 at 21:45 Comment(0)
N
1

cast the numerator to decimal

CAST(Non_Updated) as decimal / Total_Devices

for e.g.
select cast(3 as decimal)/4 ;

Northumbria answered 27/7, 2022 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.