How do I CAST AS DECIMAL in postgresql?

我的未来我决定 提交于 2020-01-04 04:05:33

问题


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;

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/54487440/how-do-i-cast-as-decimal-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!