Reputation: 1491
Lets say I have such a table:
id|time|operation
1 2 read
2 5 write
3 3 read
4 7 read
5 2 save
6 1 open
and now I would like to do two things:
So that my query would result only into two rows.
What I got so far is:
select
sum(time) as total_time,
operation
group by
operation
;
Although that gives me many groups, depending on the number of distinct operations.
How I could group them only into two categories?
Cheers!
Upvotes: 1
Views: 3601
Reputation: 33809
Try
SELECT T.op, sum(T.time)
FROM ( SELECT time, CASE operation
WHEN 'read' THEN 'read' ELSE 'not read' END AS op ) T
GROUP BY T.op
Upvotes: 0
Reputation:
Alternatively, you can also use a case
statement:
select
case when operation != 'read' then 'other'
else operation end as operation
,sum(time) as total_time
from table
group by case when operation != 'read' then 'other'
else operation end;
Upvotes: 0
Reputation: 360662
group by
can take arbitrary clauses, so
GROUP BY (operation = 'read')
will work. Essentially you'd be grouping on the boolean result of the comparison, not the value of the operation field, so any record which is "read" will be group 1
, and any non-read will be group 0
.
Upvotes: 5