Is there an easy way to do multiple SUMs in the one query, with different criteria used for each SUM, effectively resulting in a set of subtotal columns?
Here is a simple example of what I am talking about. Say we have the following table structure to store employee shifts:
What I want is to sum shift lengths grouped by shift_category, but have the subtotals appear as separate columns, instead of getting extra rows as you would with a GROUP BY. Eg my output should look like this:
I know I could do this by joining on the table 3 times, eg
However, in practice I am not doing this on a single table but a subquery which is already pretty massive, so I wanted to avoid doing it like this. Is there some elegant way of achieving what I am after?
Here is a simple example of what I am talking about. Say we have the following table structure to store employee shifts:
Code:
Column | Type | Modifiers --------------------+-----------------------+------------------------------- shift_id | integer | not null employee_id | integer | not null shift_date | date | not null start_time | numeric(4,2) | not null end_time | numeric(4,2) | not null shift_category | character varying(32) |
Code:
employee_id | standard | weekend | holiday
-------------+----------+---------+--------
763 | 150.00 | 14.50 | 9.50
107 | 145.25 | 12.25 | 6.25
784 | 167.00 | 31.00 | 6.00
Code:
SELECT * FROM (select employee_id, SUM(end_time - start_time) FROM shift WHERE category='standard' GROUP BY employee_id) AS standard, (select employee_id, SUM(end_time - start_time) FROM shift WHERE category='weekend' GROUP BY employee_id) AS weekend, (select employee_id, SUM(end_time - start_time) FROM shift WHERE category='holiday' GROUP BY employee_id) AS holiday WHERE standard.employee_id=weekend.employee_id AND weekend.employee_id=holiday.employee_id;
Comment