views:

60

answers:

2

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?

+1  A: 
SELECT user_id, billable, sum(end - start) AS billable_time 
GROUP BY user_id,billable;
dnagirl
That's not at all what I was looking for. I thought it was obvious, but I suppose I'd better clear up the question.
Chris R
it's faster and easier to do the presentation in the application layer. My other answer will give you the layout you want at the expense of speed.
dnagirl
I agree. However, I've been told "Put it in the database"So, it's either this, or a cron job to update a table with the same structure. Faugh.
Chris R
+3  A: 
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
dnagirl
That gives me this error: ERROR: syntax error at or near "CASE"LINE 1: ...(CASE billable WHEN TRUE THEN ended - started END CASE) AS p...
Chris R
All you have to do is change `end case` to `end` and it works. Thanks!
Chris R
Sorry about that, I used MySQL stored procedure syntax by mistake.
dnagirl