2

I am using PostgreSQL and have a table like this: See the sql fiddle here: http://sqlfiddle.com/#!1/253b4/1

CREATE TABLE usage_sample
(
  id serial primary key, 
  category text NOT NULL,
  name text NOT NULL,
  sample_time timestamp with time zone NOT NULL
);

I need to write a query that returns a count for the number of samples within each minute and have this set of counts for each combination of category and name. So the output we be something like:

cat1, act1, minute1, count
cat1, act1, minute2, count
cat1, act2, minute1, count
cat1, act2, minute3, count
cat2, act1, minute2, count
...

I know how to get a count for each minute using group by and how to get a count for each combo of category and action, but I can't figure out how to combine these so I can nest the groupings and counts.

The sql fiddle http://sqlfiddle.com/#!1/253b4/1 shows an example data set and the queries I have tried to start with. Can anyone give me advice on how to get the result I need?

1 Answer 1

4

Is this what you want?

select category, name, date_trunc('minute', sample_time) as minute, count(*) 
from usage_sample 
group by category, name, date_trunc('minute', sample_time)
order by category, name, minute
Sign up to request clarification or add additional context in comments.

1 Comment

That works. Not quite sure why I didn't see that before. Thanks. I have an updated fiddle here: sqlfiddle.com/#!1/785a0/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.