Question

I have a table that contains intervals:

CREATE TABLE tbl (
    user_id: INTEGER,
    start: TIMESTAMP,
    end: TIMESTAMP,
    billable: BOOLEAN
);

I want to create a view that looks like this:

user_id | billable_time | unbillable_time

I can get one of these two using a query like this:

SELECT user_id, sum(end - start) AS billable_time WHERE billable = TRUE GROUP BY user_id;

However, I need both columns, with unbillable time being the equivalent:

SELECT user_id, sum(end - start) AS unbillable_time WHERE billable = FALSE GROUP BY user_id;

How can I get those two values into one query?

Was it helpful?

Solution

select user_id, sum(case billable when 1 then (end - start) end) as can_bill,
  sum(case billable when 0 then (end - start) end) as unbillable

OTHER TIPS

SELECT user_id, billable, sum(end - start) AS billable_time 
GROUP BY user_id,billable;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top