Skip to content
Advertisement

How to calculate percentage of availability using 2 sql query and combining it into result

I have to create a service availability using info from this 2 query.

First Query.

SELECT
  time_bucket('600s',"time") AS "time",
  count(availability)*30 AS "Reporting Period"
FROM query_response_time
WHERE
  "time" BETWEEN '2020-12-19T15:00:00Z' AND '2020-12-19T16:00:00Z' AND
  cnode = 'PDSAPUJDC' AND   
  node = 'dnsvgitndnsnode06.local' AND
  query = 'www.mampu.gov.my'
GROUP BY 1
ORDER BY 1;

example result

          time          | Reporting Period 
------------------------+------------------
 2020-12-19 23:00:00+08 |              600
 2020-12-19 23:10:00+08 |              570
 2020-12-19 23:20:00+08 |              600
 2020-12-19 23:30:00+08 |              600
 2020-12-19 23:40:00+08 |              570
 2020-12-19 23:50:00+08 |              600
 2020-12-20 00:00:00+08 |               30
(7 rows)

second query

SELECT
  time_bucket('600s',"time") AS "time",
  count(availability)*30 AS "Unplanned Outage"
FROM query_response_time
WHERE
  "time" BETWEEN '2020-12-19T15:00:00Z' AND '2020-12-19T16:00:00Z' AND
  availability = 'false' AND
  cnode = 'PDSAPUJDC' AND
  node = 'dnsvgitndnsnode06.local' AND
  query = 'www.mampu.gov.my'
GROUP BY 1
ORDER BY 1;

example result

          time          | Reporting Period 
------------------------+------------------
 2020-12-19 23:16:00+08 |               30
 2020-12-19 23:41:00+08 |               30
(2 rows)

The formula as below ((Reporting Period – Unplanned Outage)/Reporting Period)*100

Advertisement

Answer

Consider using conditional aggregation:

SELECT
  time_bucket('600s',"time") AS "time",
  count(*) * 30 AS "Reporting Period",
  count(*) filter(where availability = 'false') * 30 as AS "Unplanned Outage"
  (count(*) -  count(*) filter(where availability = 'false')) 
    / count(*) * 100.0 as "Service Availability"
FROM query_response_time
WHERE
  "time" BETWEEN '2020-12-19T15:00:00Z' AND '2020-12-19T16:00:00Z' AND
  cnode = 'PDSAPUJDC' AND   
  node = 'dnsvgitndnsnode06.local' AND
  query = 'www.mampu.gov.my'
GROUP BY 1
ORDER BY 1;

The availability computation could probably be simplified:

avg((availability <> 'false')::int) * 100 as "Service Availability"
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement