David Martin
David Martin

Reputation: 347

sqlite3 join query from single table

A sqlite3 db table contains device perf data with two columns.. device and value.

Content is something like this

deviceA|50
deviceB|75
deviceA|125
deviceB|25
deviceA|99
deviceB|10
deviceA|101
and on and on

For each device

  1. I want to know how many entries are in the table (total)
  2. I want to know how mnay entries are over threshold of 100 (overthreshold)
  3. I want to know how many entries are under threshold of 100 (underthreshold)
  4. I want to know the percent of total entries under threshold (percent)

This is my query so far

    select distinct(total.device),
       total.count,
       overthreshold.count,
       round(((total.count*1.0 - overthreshold.count)/total.count),4)*100
    from
    (select device,count(*) as count from perfdata group by device) as total
      inner join (
        select device,count(*) as count from perfdata where value>100 group by device
      ) as overthreshold
    group by overthreshold.device;

deviceA only results included here

deviceA|2017|16|99.21

deviceA had 2017 entries in the table, 16 of which are > 100; 99.21% under threshold.

for all device/value combinations, output currently only shows those overthreshold as my query tells it to.

deviceB is never overthreshold and isn't in query output (100% under threshold).

Any advice on where/how would I add in the

    select device,count(*) as count from perfdata where value<100 group by device

statement to get underthreshold returned back for inclusion in my calculation?

Thanks for any help.

Upvotes: 0

Views: 54

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269783

You want to use conditional aggregation. This is where you use the case statement along with the aggregation functions:

select device, count(*) as TotalCount,
       sum(case when value > 100 then 1 else 0 end) as OverThreshhold,
       sum(case when value < 100 then 1 else 0 end) as UnderThreshhold,
       100.0 * avg(case when value < 100 then 1.0 else 0.0 end) as PercentageUnder
from perfdata
group by device;

Upvotes: 1

Related Questions