I haven't used crosstab
function and can't test it now (there's no tablefunc extension on sqlfiddle), but in general I'd prefer simple SQL if I need such a pivot:
select
date,
hour,
sum(case when cause = 0 then c_p else 0 end) cause_0,
sum(case when cause = 1 then c_p else 0 end) cause_1
from t
group by date, hour
order by hour
I think it's easier to maintain and read it in the future (but this is subjective opinion).
update This one works (hour used as a row_name
, date and name are extra
columns):
SELECT * from crosstab (
'select hour, date, name, cause, sum(c_p) as c_p
from t
group by 1, 2, 3, 4
order by 1',
'select distinct cause from t order by 1')
AS t_pivot (hour integer, date timestamp, name integer, cause_0 integer,cause_1 integer)
From documentation:
source_sql is a SQL statement that produces the source set of data. This statement must return one row_name column, one category column, and one value column. It may also have one or more "extra" columns. The row_name column must be first. The category and value columns must be the last two columns, in that order. Any columns between row_name and category are treated as "extra". The "extra" columns are expected to be the same for all rows with the same row_name value.
also
In practice the source_sql query should always specify ORDER BY 1 to ensure that values with the same row_name are brought together. However, ordering of the categories within a group is not important. Also, it is essential to be sure that the order of the category_sql query's output matches the specified output column order.