drop table if exists states;
create table states (
datetime datetime,
level text,
critical text
);
insert into states (level, critical) values ('Level1', 'Red');
insert into states (level, critical) values ('Level1', 'Red');
insert into states (level, critical) values ('Level1', 'Yellow');
insert into states (level, critical) values ('Level2', 'Green');
insert into states (level, critical) values ('Level2', 'Red');
insert into states (level, critical) values ('Level3', 'Green');
insert into states (level, critical) values ('Level3', 'Yellow');
insert into states (level, critical) values ('Level3', 'Green');
create index if not exists idx_level on states (level);
create index if not exists idx_critical on states (critical);
select level, critical, count(*) as statistic
from
(
select level,
case when
(level <> 'Level1') and (level <> 'Level2')
then critical
else ''
end as critical
from states)
group by level, critical;
or
select level, '' as critical, count(*) as count from states
where
(level='Level1') or (level='Level2')
group by 1
union all
select level, critical, count(*) as count from states
where
(level <> 'Level1') and (level <> 'Level2')
group by 1, 2
order by 1,2;
Level 1,2,etc are just aliases for proper strings, thus it is not possible to use operators as "<" or ">" on strings here. Both fields have indices.
Thanks to both of you.
Furthermore, what would be faster? I believe nested select is always slower, but all depends on internal engine optimization