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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With